CHAPTER 5 UNDERSTANDING ENCAPSULATION
If you want to be very clear about this, it is permissible to explicitly call the default constructor as
follows:
// Here, the default constructor is called explicitly.
Point finalPoint = new Point() { X = 30, Y = 30 };
Do be aware that when you are constructing a type using the new initialization syntax, you are able
to invoke any constructor defined by the class. Our Point type currently defines a two-argument
constructor to set the (x, y) position. Therefore, the following Point declaration results in an X value of
100 and a Y value of 100, regardless of the fact that our constructor arguments specified the values 10 and
16:
// Calling a custom constructor.
Point pt = new Point(10, 16) { X = 100, Y = 100 };
Given the current definition of your Point type, calling the custom constructor while using
initialization syntax is not terribly useful (and more than a bit verbose). However, if your Point type
provides a new constructor that allows the caller to establish a color (via a custom enum named
PointColor), the combination of custom constructors and object initialization syntax becomes clear.
Assume you have updated Point as follows:
public enum PointColor
{ LightBlue, BloodRed, Gold }
class Point
{
public int X { get; set; }
public int Y { get; set; }
public PointColor Color{ get; set; }
public Point(int xVal, int yVal)
{
X = xVal;
Y = yVal;
Color = PointColor.Gold;
}
public Point(PointColor ptColor)
{
Color = ptColor;
}
public Point()
: this(PointColor.BloodRed){ }
public void DisplayStats()
{
Console.WriteLine("[{0}, {1}]", X, Y);
Console.WriteLine("Point is {0}", Color);
}
}
With this new constructor, you can now create a gold point (positioned at 90, 20) as follows:
205