Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why child class variable initialize before parent class member variable

Consider the code below. Fields i and j are initialized before m and n. We know that the parent object is created before the child object, but in my program the compiler is allocating and initializing memory for the child class' member variables before the base class'. Why is that?

class X
{
    private int m = 0;
    private int n = 90;
    public X() { }
}

class Y:X
{
    private int i = 8;
    private int j = 6;
    public Y()
    { }
    public static void Main(string []args)
    {
        Y y1 = new Y();  
    }
}
like image 875
AmitykSharma Avatar asked Mar 22 '23 04:03

AmitykSharma


1 Answers

This is explained in Eric Lippert's blog:

[...] an initialized readonly field is always observed in its initialized state, and we cannot make that guarantee unless we run all the initializers first, and then all of the constructor bodies.

Not sure why readonly is mentioned here, but for example, this ensures that the following scenarios, albeit being stupid, work:

1.

class Base
{
    public Base()
    {
        if (this is Derived) (this as Derived).Go();
    }
}

class Derived : Base
{
    X x = new X();

    public void Go()
    {
        x.DoSomething(); // !
    }
}

2.

class Base
{
    public Base()
    {
        Go();
    }

    public virtual Go() {}
}

class Derived : Base
{
    X x = new X();

    public override void Go()
    {
        x.DoSomething(); // !
    }
}

This order is explicitly stated in C# Language Specification (17.10.2):

[...] constructor implicitly performs the initializations specified by the variable-initializers of the instance fields declared in its class. This corresponds to a sequence of assignments that are executed immediately upon entry to the constructor and before the implicit invocation of the direct base class constructor.

like image 68
BartoszKP Avatar answered Apr 06 '23 22:04

BartoszKP