Chaining constructors with inheritance

Technorati Tags:

So I was just wondering, what happens if I have chained constructors in a class that inherits from an abstract class that has chained constructors.

I have this abstract class:

public abstract class MyAbstract
{
    public MyAbstract(string name) : this()
    {
        Console.WriteLine("MyAbstract name constructor executed!");
    }

    public MyAbstract()
    {
        Console.WriteLine("MyAbstract default constructor executed!");
    }
}

And this class that inherits from the abstract class:

public class MyClass : MyAbstract
{
        public MyClass (string name) : base(name)
        {
            Console.WriteLine("MyClass name constructor executed!");
        }

        public MyClass() : base()
        {
            Console.WriteLine("MyClass default constructor executed!");
        }
}

So the big question is if I do a new MyClass(“Name”), what will happen?

What I want to happen is of course that all 4 constructors should run. But will the default constructor on the ever get called, or does it execute the called constructor for then going to the abstract class and execute the chained constructors there?

The answer is the latter. First the default constructor on the abstract is called, then the name constructor on the abstract, and then the name constructor in MyClass.

In my case I could easily get around it, because I was only setting a property. A default value on the property solves that. Like this:

[DefaultValue(false)]
public bool ReplyReceived { get; set; }

But if you want to execute methods in all the different constructors, I guess the best way is to create a private method in the MyClass. So I changed the MyClass to look like this:

public class MyClass : MyAbstract
{
    public MyClass (string name) : base(name)
    {
        Console.WriteLine("Name constructor in MyClass executed!");
        MyClassInit();
    }

    public MyClass() : base()
    {
        MyClassInit();
    }

    private static void MyClassInit()
    {
        Console.WriteLine("Default constructor in MyClass executed!");
    }
}

Here is a blog post from Eric Lippert explaining some things about why it is implemented like this.

 

Leave a comment