Given the two classes below, I would like to call the Child constructor with the int parameter, then the parent constructor with the int parameter and last the Child parameterless constructor.
Can this be done without the use of optional parameters?
public class Parent
{
public Parent()
{
Console.WriteLine("Parent ctor()");
}
public Parent(int i)
{
Console.WriteLine("Parent ctor(int)");
}
}
public class Child:Parent
{
public Child()
{
Console.WriteLine("Child ctor()");
}
public Child(int i)
{
Console.WriteLine("Child ctor(int)");
}
}
Here is the logic in .NET 4 we want to accomplish in .NET 2.0
public class Parent2
{
public Parent2(int? i = null)
{
Console.WriteLine("Parent2 ctor()");
if (i != null)
{
Console.WriteLine("Parent2 ctor(int)");
}
}
}
public class Child2 : Parent2
{
public Child2(int? i = null)
: base(i)
{
Console.WriteLine("Child2 ctor()");
if (i != null)
{
Console.WriteLine("Child2 ctor(int)");
}
}
}
Here is the production code we were discussing
public class DataPoint<T>
{
public DataPoint() { }
public DataPoint(T xValue, int yValue)
{
XAxis = xValue;
YAxis = yValue;
}
public T XAxis { get; set; }
public int YAxis { get; set; }
}
public class DataPointCollection<T> : DataPoint<T>
{
DataPointCollection()
{
Labels = new List<string>();
}
DataPointCollection(T xValue, int yValue)
: base(xValue, yValue)
{ }
public List<string> Labels { get; set; }
}
EDIT:
At this point the reason for the question is a "Code Golf" academic exercise to follow a DRY methodology in the least amount of code. The normal pattern is to use an internal private function in the class that has the common code to execute from each of the constructors.
EDIT 2
I added the example production code.