CHAPTER 5 UNDERSTANDING ENCAPSULATION
// Calling a more interesting custom constructor with init syntax.
Point goldPoint = new Point(PointColor.Gold){ X = 90, Y = 20 };
goldPoint.DisplayStats();
Initializing Inner Types
As briefly mentioned earlier in this chapter (and fully examined in Chapter 6), the “has-a” relationship
allows us to compose new classes by defining member variables of existing classes. For example, assume
you now have a Rectangle class, which makes use of the Point type to represent its upper-left/bottomright coordinates. Since automatic properties set all internal class variables to null, you will implement
this new class using “traditional” property syntax:
class Rectangle
{
private Point topLeft = new Point();
private Point bottomRight = new Point();
public Point TopLeft
{
get { return topLeft; }
set { topLeft = value; }
}
public Point BottomRight
{
get { return bottomRight; }
set { bottomRight = value; }
}
public void DisplayStats()
{
Console.WriteLine("[TopLeft: {0}, {1}, {2} BottomRight: {3}, {4}, {5}]",
topLeft.X, topLeft.Y, topLeft.Color,
bottomRight.X, bottomRight.Y, bottomRight.Color);
}
}
Using object initialization syntax, you could create a new Rectangle variable and set the inner
Points as follows:
// Create and initialize a Rectangle.
Rectangle myRect = new Rectangle
{
TopLeft = new Point { X = 10, Y = 10 },
BottomRight = new Point { X = 200, Y = 200}
};
Again, the benefit of object initialization syntax is that it basically decreases the number of
keystrokes (assuming there is not a suitable constructor). Here is the traditional approach to establishing
a similar Rectangle:
// Old-school approach.
Rectangle r = new Rectangle();
Point p1 = new Point();
206