Tuesday, April 22, 2008

Initializer Running in The Opposite Order as Constructors

What would be the output of this C# program be?

class Program
{
static void Main(string[] args)
{
new Derived();
}
}

public class Base
{
A ob = new A("Initialized base A");
public Base() { Console.WriteLine("In base constructor");}
}

public class Derived : Base
{
A ob = new A("Initialized derived A");
public Derived() { Console.WriteLine("In derived constructor");}
}

public class A
{
public A(string str) { Console.WriteLine(str);}
}

if your answer was :
Initialized base A
In base constructor
Initialized derived A
In derived constructor
Then you are wrong !!!, actually the answer is

Initialized derived A
Initialized base A
In base constructor
In derived constructor
Weird right?, the order is reversed, the initializers are called first in the order derived then base, then
the constructors get called from base to derived.

Imagine that one day you thought of putting a abstract method in the class Base and which you implement in the Derived class , but the
implimentaion of the abstract method in Derived accesses a instance variable in the Derived class.
In this instance if the initializers ran in the order of the constructors , you will end up with a null point exception.

although this looks reasonable, it also means the you can call a method in the Derived class from the Base class even without calling
the Derived constructor...how weired is that.

No comments:

Post a Comment