Free mag vol1 | Page 262

CHAPTER 5  UNDERSTANDING ENCAPSULATION Console.WriteLine("Pay: {0}", Pay); } // Properties as before... ... } Read-Only and Write-Only Properties When encapsulating data, you might want to configure a read-only property. To do so, simply omit the set block. Likewise, if you want to have a write-only property, omit the get block. For example, assume you wanted a new property named SocialSecurityNumber, which encapsulates a private string variable named empSSN. If you want to make this a read-only property, you could write: public string SocialSecurityNumber { get { return empSS; } } Now assume our class constructor has a new parameter to let the caller set the SSN of the object. Since the SocialSecurityNumber property is read only, we cannot set the value as so: public Employee(string name, int age, int id, float pay, string ssn) { Name = name; Age = age; ID = id; Pay = pay; // OOPS! This is no longer possible if the property is read // only. SocialSecurityNumber = ssn; } Unless we are willing to redesign the property as read/write, your only choice would be to use the underlying empSSN member variable within your constructor logic as so: public Employee(string name, int age, int id, float pay, string ssn) { ... empSSN = ssn; } To wrap up the story thus far, recall that C# prefers properties to encapsulate data. These syntactic entities are used for the same purpose as traditional accessor (get)/mutator (set) methods. The benefit of properties is that the users of your objects are able to manipulate the internal data point using a single named item.  Source Code The EmployeeApp project can be found under the Chapter 5 subdirectory. 198