You made me… now tell me what to do

The question came up at work as to why a warning was issued against the call to DoSomething in the following code.

public class A
{
    public A()
    {
        DoSomething();
    }
    protected virtual void DoSomething()
    {
    }
}

The answer is, of course, that the virtual call can end up calling back into a derived class before it has fully finished initialising. For example, the following derived class

public class B : A
{
    int x;
    public B()
    {
        x = 33;
    }
    protected override void DoSomething()
    {
        Console.WriteLine(x);
    }
}

when called as

  var b = new B();

ends up printing 0, as the virtual class runs one of the methods inside B before the constructor has finished running.

This brings up the interesting point that generally constructors should prepare a class for use, but should probably leave complicated actions such as subscribing to events or complicated setup to a subsequent initialization method call. Indeed, if a constructor throws an exception, then it is easy for a finaliser action to see a partially constructed object causing the finaliser to fail in interesting ways.

Advertisements
This entry was posted in Computers and Internet. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s