Reverse the order of constructor calls by inheriting constructor
I have a class that first needs to call the derived class constructor before it calls the base constructor. I know that in the following code, the base constructor will be called first:
public class A {
protected A () {
//do something
}
}
public class B : A {
public B () : base() {
//do something else
}
}
Is this a way to reverse this order or a workaround? One possible solution is where we create an additional protected method in the base class like doConstructor () and call it in the derived constructor after the first task is not possible with readonly fields because the compiler will not accept it.
source to share
There is no direct way to do this. I ran into this situation before too and used a method Initialize
to get around it.
public class A
{
protected A()
{
// Do pre-initialization here still.
Initialize();
}
protected virtual Initialize()
{
// Do all post-derived-class initialization here.
}
}
public class B : A
{
public B()
: base()
{
}
protected override Initialize()
{
// Do initialization between pre- and post- initialization here.
base.Initialize();
}
}
If you follow the pre-, post-, and normal initialization guidelines here, it might be reasonably safe and in good practice.
source to share