Do not call overridable methods in constructors – C#

Posted: December 6, 2010 in C#
Tags:
using System;

namespace Sample
{
    public class Base
    {
        protected  string initialized = "No";

        public Base()
        {
            Console.WriteLine( "Calling base ctor." );
            DoSomething();
        }
        // This will be overridden in the derived type.
        public virtual void DoSomething()
        {
            Console.WriteLine( "Base DoSomething" );
        }
    }

    public class DerivedType : Base
    {
        public DerivedType ()
        {
            Console.WriteLine( "Calling derived ctor." );
            initialized = "Yes";
        }
        public override void DoSomething()
        {
            Console.WriteLine( "Derived DoSomething is called - initialized ? {0}", initialized );
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Base derivedInstance = new DerivedType();
        }
    }
}

Output:
Calling base ctor.
Derived DoSomething is called - initialized ? No
Calling derived ctor.

Is there something wrong ? … Yes of course, when constructing the derived class, the base class is constructed first. If we call a virtual method from the constructor of base class, the overridden method is called. But the point to be noticed is that when that overridden method is called, the derived class is not initialized because its constructor code was not yet executed. So in this case we are calling a method of an un-initialized instance.

Please refer MSDN for more details.

The interesting fact is that, this behavior is just opposite in case of C++. Kindly refer my previous post Behavior of virtual functions in constructors – C++ for more details.

Advertisements

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