Tutorial :C# equivalent of Java instance initializer



Question:

In Java instance variables can be initialized by an initialization block as shown below:

class Example {      private int varOne;      private int varTwo;        {          // Instance Initializer          varOne = 42;          varTwo = 256;      }  }  

Is there an equivalent construct in C#?

[Edit] I know that this can be inline with the instance variable declaration. However, I am looking for is something similar to the static constructor in C# but for instance variables.


Solution:1

There really is no equivalent in C#. C# has only 2 ways to initialize instance varibles

  1. In the constructor
  2. By explicitly initializing the variable at it's declaration point

There is no way to do an initialization after the object is created but before the constructor runs.


Solution:2

Create an instance constructor that any other local constructor will call in the initialization list:

private Example ()  {      //initialize all fields here  }    public Example (/*list of parameters*/) : this()  {      //do specific work here  }  

If the default constructor is already required by the logic of the application, then susbstitute

private Example ()  

with

private Example (object dummy)  

and, of course, accordingly modify the initilization call.


Solution:3

If this is what you want for specific case then extent that it's possible is as below :

class Example {      public int varOne;      public int varTwo;        public Example(){          Console.WriteLine("varOne : " + varOne + ", varTwo : " + varTwo);      }        public void getValues()      {          Console.WriteLine("varOne : " + varOne + ", varTwo : " + varTwo);      }  }    static void Main(string[] args)      {          Example e = new Example{ varOne = 42, varTwo = 256};          e.getValues();      }  

Here, then there is a constraint that you would require instance variables to be public.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »