CHAPTER 4 CORE C# PROGRAMMING CONSTRUCTS, PART II
}
}
Here, you have defined your two integer fields (X and Y) using the public keyword, which is an
access control modifier (Chapter 5 furthers this discussion). Declaring data with the public keyword
ensures the caller has direct access to the data from a given Point variable (via the dot operator).
Note It is typically considered bad style to define public data within a class or structure. Rather, you will want
to define private data, which can be accessed and changed using public properties. These details will be
examined in Chapter 5.
Here is a Main() method that takes our Point type out for a test drive:
static void Main(string[] args)
{
Console.WriteLine("***** A First Look at Structures *****\n");
// Create an initial Point.
Point myPoint;
myPoint.X = 349;
myPoint.Y = 76;
myPoint.Display();
}
// Adjust the X and Y values.
myPoint.Increment();
myPoint.Display();
Console.ReadLine();
The output is as you would expect:
***** A First Look at Structures *****
X = 349, Y = 76
X = 350, Y = 77
Creating Structure Variables
When you want to create a structure variable, you have a variety of options. Here, you simply create a
Point variable and assign each piece of public field data before invoking its members. If you do not
assign each piece of public field data (X and Y in our case) before making use of the structure, you will
receive a compiler error:
// Error! Did not assign Y value.
Point p1;
p1.X = 10;
147