CHAPTER 4 CORE C# PROGRAMMING CONSTRUCTS, PART II
p1.Display();
// OK! Both fields assigned before use.
Point p2;
p2.X = 10;
p2.Y = 10;
p2.Display();
As an alternative, we can create structure variables using the C# new keyword, which will invoke the
structure’s default constructor. By definition, a default constructor does not take any arguments. The
benefit of invoking the default constructor of a structure is that each piece of field data is automatically
set to its default value:
// Set all fields to default values
// using the default constructor.
Point p1 = new Point();
// Prints X=0,Y=0.
p1.Display();
It is also possible to design a structure with a custom constructor. This allows you to specify the
values of field data upon variable creation, rather than having to set each data member field by field.
Chapter 5 will provide a detailed examination of constructors; however, to illustrate, update the Point
structure with the following code:
struct Point
{
// Fields of the structure.
public int X;
public int Y;
// A custom constructor.
public Point(int XPos, int YPos)
{
X = XPos;
Y = YPos;
}
...
}
With this, we could now create Point variables, as follows:
// Call custom constructor.
Point p2 = new Point(50, 60);
// Prints X=50,Y=60.
p2.Display();
As mentioned, working with structures on the surface is quite simple. However, to deepen your
understanding of this type, you need to explore the distinction between a .NET value type and a .NET
reference type.
148