tags:

views:

397

answers:

2

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.

+1  A: 

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.

JaredPar
+2  A: 

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.

lmsasu
unfortunately that doesn't let you have multiple instance initializer blocks... but for the common case would be reasonable.
TofuBeer
Curious - what is TofuBeer? and also, why would you want multiple instance initializer blocks? For the latter - it seems it would lead to confusion with blocks scattered throughout the class code, separate from constructors and separate from the member decls.
Cheeso