Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling child class constructor before parent constructor

Tags:

c#

Is it possible to call the constructor of child class before the constructor of the parent class?

Someone said it is indeed possible with the use of a virtual method, but I can't find a way to do so.

like image 993
smriti Avatar asked Feb 27 '23 14:02

smriti


1 Answers

In IL, this is possible. In C#: no.

You can use virtual to run a method in a type before that type's ctor, but it is discouraged and risky. But:

class Foo {
    public Foo() {
        Console.WriteLine("Foo ctor");
        SomeMethod(); // BAD IDEA (calling a virtual method in a ctor)
    }
    protected virtual void SomeMethod() {}
}
class Bar : Foo {
    protected override void SomeMethod() {
        Console.WriteLine("SomeMethod in Bar");
    }
    public Bar() : base() { /* only to show call order */
        Console.WriteLine("Bar ctor");
    }
}

It is a bad idea because you can't guarantee that the subclasses are ready for the method-call.

like image 116
Marc Gravell Avatar answered Apr 07 '23 06:04

Marc Gravell