CHAPTER 5 UNDERSTANDING ENCAPSULATION
class Point
{
public int X { get; set; }
public int Y { get; set; }
public Point(int xVal, int yVal)
{
X = xVal;
Y = yVal;
}
public Point() { }
public void DisplayStats()
{
Console.WriteLine("[{0}, {1}]", X, Y);
}
}
Now consider how we can make Point objects using any of the following approaches:
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Object Init Syntax *****\n");
// Make a Point by setting each property manually.
Point firstPoint = new Point();
firstPoint.X = 10;
firstPoint.Y = 10;
firstPoint.DisplayStats();
// Or make a Point via a custom constructor.
Point anotherPoint = new Point(20, 20);
anotherPoint.DisplayStats();
}
// Or make a Point using object init syntax.
Point finalPoint = new Point { X = 30, Y = 30 };
finalPoint.DisplayStats();
Console.ReadLine();
The final Point variable is not making use of a custom constructor (as one might do traditionally),
but is rather setting values to the public X and Y properties. Behind the scenes, the type’s default
constructor is invoked, followed by setting the values to the specified properties. To this end, object
initialization syntax is just shorthand notations for the syntax used to create a class variable using a
default constructor, and setting the state data property by property.
Calling Custom Constructors with Initialization Syntax
The previous examples initialized Point types by implicitly calling the default constructor on the type:
// Here, the default constructor is called implicitly.
Point finalPoint = new Point { X = 30, Y = 30 };
204