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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With