Search code examples
c#classconstructorinitializationmember-variables

What is happening in the background when a member variable is initialized within a class but not with the help of the constructor?


Could anyone explain me the following C# sample code?

public class MyTestClass
{
    private int x = 100;
    private int y;
    
    public MyTestClass
    {
        y = 200;
    }
}

I understand that when MyTestClass is instantiated, the constructor gets called and y is assigned the value 200. But what happens in case of x? When is 100 actually assigned to x? Should I imagine this as if x were in the constructor and got its initial value there?


Solution

  • All member declarations are processed before the constructor is executed. That should be obvious because, otherwise, the fields wouldn't exist to be set in the constructor. If a field is initialised where it's declared, that assignment happens when the member is processed. That means that, in your case, x already has the value 100 when the constructor code is executed. You can think of initialised fields like that as being populated pretty much as struct fields are, which happens without an explicit constructor.