CHAPTER 5 UNDERSTANDING ENCAPSULATION
}
...
}
intensity = 10;
}
driverIntensity = intensity;
driverName = name;
Understand that using the this keyword to chain constructor calls is never mandatory. However,
when you make use of this technique, you do tend to end up with a more maintainable and concise class
definition. Again, using this technique you can simplify your programming tasks, as the real work is
delegated to a single constructor (typically the constructor that has the most parameters), while the
other constructors simply “pass the buck.”
Note Recall from Chapter 4 that C# supports optional parameters. If you make use of optional parameters in
your class constructors, you can achieve the same benefits as constructor chaining, with considerably less code.
You will see how to do so in just a moment.
Observing Constructor Flow
On a final note, do know that once a constructor passes arguments to the designated master constructor
(and that constructor has processed the data), the constructor invoked originally by the caller will finish
executing any remaining code statements. To clarify, update each of the constructors of the Motorcycle
class with a fitting call to Console.WriteLine():
class Motorcycle
{
public int driverIntensity;
public string driverName;
// Constructor chaining.
public Motorcycle()
{
Console.WriteLine("In default ctor");
}
public Motorcycle(int intensity)
: this(intensity, "")
{
Console.WriteLine("In ctor taking an int");
}
public Motorcycle(string name)
: this(0, name)
{
Console.WriteLine("In ctor taking a string");
}
174