Free mag vol1 | Page 256

CHAPTER 5  UNDERSTANDING ENCAPSULATION Console.WriteLine("ID: {0}", empID); Console.WriteLine("Pay: {0}", currPay); } } Notice that the fields of the Employee class are currently defined using the private keyword. Given this, the empName, empID, and currPay fields are not directly accessible from an object variable. Therefore, the following logic in Main() would result in compiler errors: static void Main(string[] args) { // Error! Cannot directly access private members // from an object! Employee emp = new Employee(); emp.empName = "Marv"; } If you want the outside world to interact with a worker’s full name, a traditional approach (which is very common in Java) is to define an accessor (get method) and a mutator (set method). The role of a “get” method is to return to the caller the current value of the underlying state data. A “set” method allows the caller to change the current value of the underlying state data, as long as the defined business rules are met. To illustrate, let’s encapsulate the empName field. To do so, add the following public methods to the Employee class. Notice that the SetName() method performs a test on the incoming data, to ensure the string is 15 characters or less. If it is not, an error prints to the console and returns without making a change to the empName field:  Note If this were a production level class, you would also make to check the character length for an employee’s name within your constructor logic. Ignore this detail for the time being, as you will clean up this code in just a bit when you examine .NET property syntax. class Employee { // Field data. private string empName; ... // Accessor (get method). public string GetName() { return empName; } // Mutator (set method). public void SetName(string name) { // Do a check on incoming value // before making assignment. 192