
274
LESSON 23 Defining Classes
code asserts that the new value is between 0 and 359 degrees. The program can continue correctly if
the value is outside of this range so the code uses
Debug.Assert instead of throwing an exception.
// The Turtle’s direction in degrees.
private int direction = 0; // Backing field.
public int Direction
{
get { return direction; }
//set { direction = value; }
set
{
Debug.Assert((value >= 0) && (value <= 359),
“Direction should be between 0 and 359 degrees”);
direction = value;
}
}
Property accessors also give you a place to set break-
points if something is going wrong. For example, if
you know that some part of your program is setting
a
Turtle’s Direction to 45 when it should be set-
ting it to 60 but you don’t know where, you could set
a breakpoint in the
set accessor to see where the
change is taking place.
TRY IT
In this first Try It in the lesson, you cre-
ate a simple
Person class with FirstName,
LastName, City, Street, and Zip properties,
some having simple validations. You also build
a simple test application shown in Figure 23-1.
You can download the code and resources for this Try It from the book’s web
page at
www.wrox.com or www.CSharpHelper.com/24hour.html. You can find
them in the TryIt23a folder in the Lesson23 folder of the download.
Lesson Requirements
Build the program shown in Figure 23-1.
Create a
Person class.
Make auto-implemented properties ...