Call Virtual Functions From Constructors?Take a look at the following code, can you tell what will the output be?
public class BaseType
{
public BaseType()
{
Console.WriteLine("Call base Sector.");
DoSomething();
}
public virtual void DoSomething()
{
Console.WriteLine("Base DoSomething");
}
}
public class DerivedType : BaseType
{
public DerivedType()
{
Console.WriteLine("Call derived Sector.");
}
public override void DoSomething()
{
Console.WriteLine("Derived DoSomething");
}
}
public class MainClass
{
public static void Main()
{
DerivedType derived = new DerivedType();
Console.ReadLine();
}
}
The output of this program is:
Call base Sector.
Derived DoSomething.
Call derived Sector.
Can you see the problem here? There is something very wrong and dangerous in this code…
Explanation: When constructing the derived class, the base class is constructed first. If you call a virtual method from the base class constructor, the overridden method is called. But notice that when that overridden method is called, the derived class is not initialized because its constructor code was not executed yet. So, we are calling a method of an un-initialized instance… This is the explanation from MSDN: “When a virtual method is called, the actual type that executes the method is not selected until run time. When a constructor calls a virtual method, it is possible that the constructor for the instance that invokes the method has not executed“.
Be aware of this matter because it is not a trivial issue and apparently, there are no errors or warnings generated by the compiler. So, the rule to remember is to never call virtual methods from constructors. Now, go and check your code, is there a possibility that you violated this rule?