CHAPTER 5 UNDERSTANDING ENCAPSULATION
}
if (name.Length > 15)
Console.WriteLine("Error!
else
empName = name;
Name must be less than 16 characters!");
}
This technique requires two uniquely named methods to operate on a single data point. To test your
new methods, update your Main() method as follows:
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Encapsulation *****\n");
Employee emp = new Employee("Marvin", 456, 30000);
emp.GiveBonus(1000);
emp.DisplayStats();
}
// Use the get/set methods to interact with the object's name.
emp.SetName("Marv");
Console.WriteLine("Employee is named: {0}", emp.GetName());
Console.ReadLine();
Because of the code in your SetName() method, if you attempted to specify more than 16 characters
(see the following), you would find the hard-coded error message printed to the console:
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Encapsulation *****\n");
...
// Longer than 16 characters! Error will print to console.
Employee emp2 = new Employee();
emp2.SetName("Xena the warrior princess");
Console.ReadLine();
}
So far, so good. You have encapsulated the private empName field using two public methods named
GetName() and SetName(). If you were to further encapsulate the data in the Employee class, you would
need to add various additional methods (such as GetID(), SetID(), GetCurrentPay(), SetCurrentPay()).
Each of the mutator methods could have within it various lines of code to check for additional business
rules. While this could certainly be done, the C# language has a useful alternative notation to
encapsulate class data.
Encapsulation Using .NET Properties
Although you can encapsulate a piece of field data using traditional get and set methods, .NET
languages prefer to enforce data encapsulation state data using properties. First of all, understand that
properties are just a simplification for “real” accessor and mutator methods. Therefore, as a class
designer, you are still able to perform any internal logic necessary before making the value assignment
(e.g., uppercase the value, scrub the value for illegal characters, check the boun G2