Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# equivalent of Java instance initializer

Tags:

java

c#

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.

like image 336
maxyfc Avatar asked Mar 28 '09 13:03

maxyfc


1 Answers

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.

like image 106
JaredPar Avatar answered Oct 11 '22 23:10

JaredPar