0

I have an abstract class:

public abstract class BaseClass
{
    protected BaseClass()
    {
        before();
        run();
        after();
    }

    protected abstract void run();

    private void before() { }

    private void after() { }
}

And the derived class which just overrides abstract run method:

public class DerivedClass
{
    public readonly ContextClass a;

    public DervidedClass(ContextClass a) =>
        this.a = a;

    protected override void run()
    {
        if (a is null)
            Console.WrileLine("a is null");
    }
}

Logically, when I create an instance of DerivedClass it calls its base constructor. In base constructor it should call before(), run() and after() methods, but when it comes to run() it is being executed with no DerivedClass context as "a" is null here.

It looks like a complete nonsense, so I guess I have an error in my code maybe. I will be grateful for your help.

  • 1
    Yes, this is expected behavior, and also why it's generally recommended not to call `virtual` or `abstract` methods in your constructor. Your `DervidedClass` constructor doesn't happen until the base class constructor is finished, so the fields aren't initialized yet. – Kirk Woll Jun 15 '22 at 17:26
  • 1
    By design, more details (expanded on what @KirkWoll said) are in [duplciate](https://stackoverflow.com/questions/119506/virtual-member-call-in-a-constructor) – Alexei Levenkov Jun 15 '22 at 17:27

0 Answers0