C# – Understanding Constructor Chaining

c

I'm trying to understand constructor chaining better. I understand that this technique can be used to reduce code duplication for initialization of a class object and I also understand the order in which they're executed.

I found the following example and I cannot see clearly what the benefits are in the code? And whether it's necessary? I don't understand why both constructors have 'this' keyword in them, would calling either constructor (and passing in relevant parameters) have the same result?

//Constructors
public MyClass(double distance, double angle) : this(distance, angle, 0) 
{
}

public MyClass(double distance, double angle, double altitude) : this()
{
Distance = distance;
Angle = angle;
Altitude = altitude;
}

Best Answer

First off, you get reduced code duplication as the top constructor is chained to the second - passing in a 0 for the altitude parameter; the other passed in parameters are passed in to the chained constructor from the values used in the constructor itself (the distance and angle parameters). The reduced duplication is in the fact that the second constructor is the one doing the initialization and it is not duplicated in the first constructor.

Another benefit is that you now have overloaded the constructor such that the altitude parameter is optional and will default to 0 if not supplied.

The second constructor is chained to a parameterless constructor that you have not shown in your example. This one may very well initialized other parts of the class - initialization that is not repeated elsewhere.


would calling either constructor (and passing in relevant parameters) have the same result?

Sure. But this is some nice syntactic sugar - makes the code easy to read and short.