C# How to execute code after object construction (postconstruction)

Viewed 30063

As you can see in the code below, the DoStuff() method is getting called before the Init() one during the construction of a Child object.

I'm in a situation where I have numerous child classes. Therefore, repeating a call to the DoStuff() method directly after Init() in the constructor of each child wouldn't be an elegant solution.

Is there any way I could create some kind of post constructor in the parent class that would be executed after the child's constructor? This way, I could call to the DoStuff() method there.

If you have any other design idea which could solve my problem, I'd like to hear it too!

abstract class Parent
{
    public Parent()
    {
        DoStuff();
    }

    protected abstract void DoStuff();
}

class Child : Parent
{
    public Child()
    // DoStuff is called here before Init
    // because of the preconstruction
    {
        Init();
    }

    private void Init()
    {
        // needs to be called before doing stuff
    }

    protected override void DoStuff() 
    {
        // stuff
    }
}
11 Answers
    class MyBase
    {
        public MyBase()
        {
            //... do something

            // finally call post constructor                
            PostConstructor<MyBase>();
        }

        public void PostConstructor<T>(  )
        {
            // check
            if (GetType() != typeof(T))
                return;

            // info
            System.Diagnostics.Debug.WriteLine("Post constructor : " + GetType());
        }
    }

    class MyChild : MyBase
    {
        public MyChild()
        {
            // ... do something

            // ... call post constructor
            PostConstructor<MyChild>();
        }
    }

How about...

public MyClass()
{
    Dispatcher.UIThread.Post(RunAfterConstructor);
}

I also tried with Task.Run but that didn't work reliably.

Related