maxyfc
maxyfc

Reputation: 11337

C# equivalent of Java instance initializer

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.

Upvotes: 8

Views: 3927

Answers (3)

Mitesh Vora
Mitesh Vora

Reputation: 458

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.

Upvotes: 1

lmsasu
lmsasu

Reputation: 7583

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.

Upvotes: 7

JaredPar
JaredPar

Reputation: 755317

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.

Upvotes: 8

Related Questions