It is simple rule, but maybe some people will find this post useful.
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."
So the reason of possible problems is that constructor of derived class will be called later then constructor of base class. And if you
call virtual method in base class constructor, overridden method of derived class will be actually executed.
And as fields of derived class were not initialized properly in constructor, you can get unexpected values (results) or even errors and
exceptions.
For instance, this code example will generate NullReferenceException because field _b was not initialized yet :
internal class BaseClass
{
protected int _a;
public BaseClass(int a)
{
_a = a;
PrintFields();
}
public virtual void PrintFields()
{
Console.WriteLine( _a);
}
}
internal class DerivedClass : BaseClass
{
private string _b;
public DerivedClass(int a, string b): base(a)
{
_b = b;
}
public override void PrintFields()
{
Console.WriteLine(string.Format("Field a = {0}, field b = {1}, length of string b is {2}", _a, _b, _b.Length));
}
}
class Program
{
static void Main(string[] args)
{
BaseClass a = new DerivedClass(5, "some string");
}
}
Read More..
 
[32134 clicks]
Published under:
Microsoft .NET Tips · · · ·