CHAPTER 5 UNDERSTANDING ENCAPSULATION
•
Control is returned to the constructor originally called, and executes any
remaining code statements.
The nice thing about using constructor chaining, is that this programming pattern will work with
any version of the C# language and .NET platform. However, if you are targeting .NET 4.0 and higher,
you can further simplify your programming tasks by making use of optional arguments as an alternative
to traditional constructor chaining.
Revisiting Optional Arguments
In Chapter 4, you learned about optional and named arguments. Recall that optional arguments allow
you to define supplied default values to incoming arguments. If the caller is happy with these defaults,
they are not required to specify a unique value, however they may do so to provide the object with
custom data. Consider the following version of Motorcycle, which now provides a number of ways to
construct objects using a single constructor definition:
class Motorcycle
{
// Single constructor using optional args.
public Motorcycle(int intensity = 0, string name = "")
{
if (intensity > 10)
{
intensity = 10;
}
driverIntensity = intensity;
driverName = name;
}
...
}
With this one constructor, you are now able to create a new Motorcycle object using zero, one, or
two arguments. Recall that named argument syntax allows you to essentially skip over acceptable default
settings (see Chapter 3).
static void MakeSomeBikes()
{
// driverName = "", driverIntensity = 0
Motorcycle m1 = new Motorcycle();
Console.WriteLine("Name= {0}, Intensity= {1}",
m1.driverName, m1.driverIntensity);
// driverName = "Tiny", driverIntensity = 0
Motorcycle m2 = new Motorcycle(name:"Tiny");
Console.WriteLine("Name= {0}, Intensity= {1}",
m2.driverName, m2.driverIntensity);
}
// driverName = "", driverIntensity = 7
Motorcycle m3 = new Motorcycle(7);
Console.WriteLine("Name= {0}, Intensity= {1}",
m3.driverName, m3.driverIntensity);
176
h