Home > database >  What is happening in the background when a member variable is initialized within a class but not wit
What is happening in the background when a member variable is initialized within a class but not wit

Time:04-26

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?

CodePudding user response:

Yes, in presented code it's like in a constructor. See IL code, generated by compiler:

.class public auto ansi beforefieldinit MyTestClass
    extends [System.Runtime]System.Object
{
    // Fields
    .field private int32 x
    .field private int32 y

    // Methods
    .method public hidebysig specialname rtspecialname 
        instance void .ctor () cil managed 
    {
        // Method begins at RVA 0x2050
        // Code size 28 (0x1c)
        .maxstack 8

        IL_0000: ldarg.0
        IL_0001: ldc.i4.s 100
        IL_0003: stfld int32 MyTestClass::x
        IL_0008: ldarg.0
        IL_0009: call instance void [System.Runtime]System.Object::.ctor()
        IL_000e: nop
        IL_000f: nop
        IL_0010: ldarg.0
        IL_0011: ldc.i4 200
        IL_0016: stfld int32 MyTestClass::y
        IL_001b: ret
    } // end of method MyTestClass::.ctor

} // end of class MyTestClass

CodePudding user response:

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.

  • Related