Wednesday, March 19, 2008

Initialization Order and Virtual Functions.

Initialization Order in C# class is a interesting area to probe. When constructing a C# object, especially one that is derived from another class , its important that we are aware of the initialization order.

Following is the usual initialization order.

1. Derived static fields
2. Derived static constructor
3. Derived instance fields
4. Base static fields
5. Base static constructor
6. Base instance fields
7. Base instance constructor
8. Derived instance constructor



What i am trying to focus in here is the way virtual functions are handled when using a derived class.

Consider following code.
class Program
{
static void Main( string[] args )
{
Derived d = new Derived();
Console.ReadLine();
}

}

class Base
{
public Base()
{
Console.WriteLine("Base Instance Constructor");
this.MyVirtual("Base");
}
public virtual void MyVirtual(string str)
{
Console.WriteLine("Base Virtual Function called from "+ str);
}
}

class Derived : Base
{
public Derived()
{
Console.WriteLine("Derived Instance Construcor");
this.MyVirtual("Derived");
}
public override void MyVirtual(string str)
{
Console.WriteLine("Derived Virtual Function called from " +str);
}
}



Following is the output.
Base Instance Constructor
Derived Virtual Function called from Base
Derived Instance Construcor
Derived Virtual Function called from Derived



As you can see, the derived virtual function is being invoked by the base class even before the derived class constructor is called. This shows why it is a bad design to call the virtual function from the constructor.