Virtual member call in a constructor

I’m getting a warning from ReSharper about a call to a virtual member from my objects constructor.

Why would this be something not to do?

1
18

In order to answer your question, consider this question: what will the below code print out when the Child object is instantiated?

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()); //NullReferenceException!?!
    }
}

The answer is that in fact a NullReferenceException will be thrown, because foo is null. An object’s base constructor is called before its own constructor. By having a virtual call in an object’s constructor you are introducing the possibility that inheriting objects will execute code before they have been fully initialized.

Leave a Comment