In a descendant class, is there a way to call both the public, parameterized constructor, as well as the protected/private constructor, while still making a call to the base class' constructor?
For example, given the following code:
using System;
public class Test
{
void Main()
{
var b = new B(1);
}
class A
{
protected A()
{
Console.WriteLine("A()");
}
public A(int val)
: this()
{
Console.WriteLine("A({0})", val);
}
}
class B : A
{
protected B()
{
Console.WriteLine("B()");
}
public B(int val)
: base(val)
{
Console.WriteLine("B({0})", val);
}
}
}
the output given is:
A()
A(1)
B(1)
However, this is what I was expecting:
A()
B()
A(1)
B(1)
Is there a way to achieve this through constructor chaining? Or should I have an OnInitialize()
type method in A
that is either abstract or virtual which is overridden in B
and called from the protected, parameter-less constructor of A
?
No, what you're looking for is not possible using only constructors. You're essentially asking the constructor chain to "branch", which is not possible; each constructor may call one (and only one) constructor either in the current class or the parent class.
The only way to accomplish this is (as you suggest) through the use of a virtual initialization function that you invoke in the base class. Ordinarily, calling virtual members from within a constructor is frowned upon, as you can cause code in a child class to execute before its constructor, but given that that's exactly what you're after, that's your only real approach here.