Sunday, January 10, 2010

calling virtual method within a constructor.

Rules-
1) Virtual method is called over the most derived object, method table is used for the most derived object.
2) Constructor is called from base to derived type.

Considering these rules, calling a virtual method inside a constuctor is unsafe for two reasons (what i can think of right now).

1. Instance may not be completely initialised for the object.
Sample Code:
class Parent
{
public Parent()
{
DoSomething();
}
protected virtual void DoSomething() {};
}

class Child : Parent
{
private string foo;
public Child() { foo = "HELLO"; }
protected override void DoSomething()
{
Console.WriteLine(foo.ToLower());
}
}

This code results in NullReference exception, since virtual method is called for the most derived type, and in this case the most derived is not completely initialised at the time virtual method is called.

2. The behaviour of the virtual method called would vary if (in future) a new class is introduced in the inheritance hierarchy.

Also, resharper shows a warning if we call a virtual method from inside a constructor. This warning would be suppressed if the type making a call to virtual method is sealed or if the method is marked as "sealed override" (then we won;t be having Risk-2).

No comments:

Post a Comment