CHAPTER 5 UNDERSTANDING ENCAPSULATION
Here is the updated Employee class, now enforcing encapsulation of each field using property syntax
rather than traditional get and set methods:
class Employee
{
// Field data.
private string empName;
private int empID;
private float currPay;
// Properties!
public string Name
{
get { return empName; }
set
{
if (value.Length > 15)
Console.WriteLine("Error!
else
empName = value;
}
}
Name must be less than 16 characters!");
// We could add additional business rules to the sets of these properties;
// however, there is no need to do so for this example.
public int ID
{
get { return empID; }
set { empID = value; }
}
public float Pay
{
get { return currPay; }
set { currPay = value; }
}
...
}
A C# property is composed by defining a get scope (accessor) and set scope (mutator) directly
within the property itself. Notice that the property specifies the type of data it is encapsulating by what
appears to be a return value. Also take note that, unlike a method, properties do not make use of
parentheses (not even empty parentheses) when being defined. Consider the commentary on your
current ID property:
// The 'int' represents the type of data this property encapsulates.
// The data type must be identical to the related field (empID).
public int ID // Note lack of parentheses.
{
get { return empID; }
set { empID = value; }
}
194