CHAPTER 5 UNDERSTANDING ENCAPSULATION
Within a “set” scope of a property, you use a token named value, which is used to represent the
incoming value used to assign the property by the caller. This token is not a true C# keyword, but is what
is known as a contextual keyword. When the token value is within the set scope of the property, it always
represents the value being assigned by the caller, and it will always be the same underlying data type as
the property itself. Thus, notice how the Name property can still test the range of the string as so:
public string Name
{
get { return empName; }
set
{
// Here, value is really a string.
if (value.Length > 15)
Console.WriteLine("Error! Name must be less than 16 characters!");
else
empName = value;
}
}
After you have these properties in place, it appears to the caller that it is getting and setting a public
point of data; however, the correct get and set block is called behind the scenes to preserve
encapsulation:
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Encapsulation *****\n");
Employee emp = new Employee("Marvin", 456, 30000);
emp.GiveBonus(1000);
emp.DisplayStats();
// Set and get the Name property.
emp.Name = "Marv";
Console.WriteLine("Employee is named: {0}", emp.Name);
Console.ReadLine();
}
Properties (as opposed to accessors and mutators) also make your types easier to manipulate, in
that properties are able to respond to the intrinsic operators of C#. To illustrate, assume that the
Employee class type has an internal private member variable representing the age of the employee. Here
is the relevant update (notice the use of constructor chaining):
class Employee
{
...
// New field and property.
private int empAge;
public int Age
{
get { return empAge; }
set { empAge = value; }
}
// Updated constructors.
public Employee() {}
195