We have the following class hierarchy:
public class Base
{
public Base()
{
// do generic initialization
}
public Base(SomeClass param1) : this()
{
// init properties that require param1
}
public Base(SomeClass param1, OtherClass param2) : this(param1)
{
// init properties that require param2
}
// ...
}
public class Derived : Base
{
public Derived()
{
// do custom initialization
}
public Derived(SomeClass param1) : this() // ???
{
// do custom initialization using param1
}
public Derived(SomeClass param1, OtherClass param2) : this(param1) // ???
{
// do custom initialization using param2
}
// ...
}
We would require Derived to run both its own initialization routines, up the chain, and the corresponding ones from the base class. How do we chain the constructors without duplicating code/running some of the constructors twice?
In the derived class chain the constructors with the least parameters to the constructor with the most parameters, and then the derived constructor with the most parameters is chained to base. Something like this:
Depending on the context, it may be better to use default(T) instead of null to indicate a missing/default value.