C# Call base class' constructor after own constructor?

user1632861 picture user1632861 · Jan 28, 2013 · Viewed 39.3k times · Source

How can I call base class' constructor after I've called my own constructor?

The problem is, base class' constructor calls an abstract method (overridden in sub class), which needs to access variable x, initialized in sub class' constructor?

Short example code:

abstract class BaseClass
{
    protected string my_string;

    protected abstract void DoStuff();

    public BaseClass()
    {
        this.DoStuff();
    }
}

class SubClass : BaseClass
{
    private TextBox tb;

    public SubClass()
        : base()
    {
        this.my_string = "Short sentence.";
    }

    protected override void DoStuff()
    {
        // This gets called from base class' constructor
        // before sub class' constructor inits my_string
        tb.Text = this.my_string;
    }
}

Edit: Based on answers, it obviously is not possible. Is there an automated way to call this.DoStuff(); on every object of SubClass once they're created? Of course I could just add this.DoStuff(); after all the other lines in sub class' constructor, but having around 100 of these classes, it feels stupid. Any other solution, or should I use the manual one?

Answer

ken2k picture ken2k · Jan 28, 2013

You can't.

Also, you generally shouldn't call virtual methods in a constructor. See this answer.


Depending on your actual code and not the simple example you wrote, you could pass values as parameters of the base constructor and the DoStuff method. For example:

abstract class BaseClass
{
    private string my_string;

    protected abstract void DoStuff(string myString);

    public BaseClass(string myString)
    {
        this.my_string = myString;
        this.DoStuff(this.my_string);
    }
}

class SubClass : BaseClass
{
    private TextBox tb;

    public SubClass()
        : base("Short sentence.")
    {
    }

    protected override void DoStuff(string myString)
    {
        tb.Text = myString;
    }
}

If it's not possible with your actual code, then writing multiple DoStuff() will do the job. Also remember to seal your SubClass class so nobody else will be able to introduce bugs by modifying the DoStuff method another time.