The Access Modifiers section, earlier in this chapter, demonstrated how you can use the private keyword to encapsulate a password, preventing access from outside the class. This type of encapsulation is often too thorough, however. For example, sometimes you might need to define fields that external classes can only read but whose values you can change internally. Alternatively, perhaps you want to allow access to write some data in a class but you need to be able to validate changes made to the data. Still one more example is the need to construct the data on the fly.
Traditionally, languages enabled the features found in these examples by marking fields as private and then providing getter and setter methods for accessing and modifying the data. The code in Listing 5.30 changes both FirstName and LastName to private fields. Public getter and setter methods for each field allow their values to be accessed and changed.
Listing 5.30. Declaring Getter and Setter Methods
Unfortunately, this change affects the programmability of the Employee class. No longer can you use the assignment operator to set data within the class, nor can you access data without calling a method.
Declaring a Property
Considering the frequency of this type of pattern, the C# designers decided to provide explicit syntax for it. This syntax is called a property (see Listing 5.31 and Output 5.5).
Listing 5.31. Defining Properties
The first thing to notice in Listing 5.31 is not the property code itself, but the code within the Program class. Although you no longer have the fields with the FirstName and LastName identifiers, you cannot see this by looking at the Program class. The API for accessing an employee's first and last names has not changed at all. It is still possible to assign the parts of the name using a simple assignment operator, for example (employee.FirstName = "Inigo").
The key feature is that properties provide an API that looks programmatically like a field. In actuality, however, no such fields exist. A property declaration looks exactly like a field declaration, but following it are curly braces in which to place the property implementation. Two optional parts make up the property implementation. The get part defines the getter portion of the property. It corresponds directly to the GetFirstName() and GetLastName() functions defined in Listing 5.30. To access the FirstName property you call employee.FirstName. Similarly, setters (the set portion of the implementation) enable the calling syntax of the field assignment:
employee.FirstName = "Inigo";
Property definition syntax uses three contextual keywords. You use the get and set keywords to identify either the retrieval or the assignment portion of the property, respectively. In addition, the setter uses the value keyword to refer to the right side of the assignment operation. When Program.Main() calls employee.FirstName = "Inigo", therefore, value is set to "Inigo" inside the setter and can be used to assign _FirstName. Listing 5.31's property implementations are the most common. When the getter is called (such as in Console.WriteLine(employee2.FirstName)), the value from the field (_FirstName) is returned.
Because the property name is FirstName, the field name changed from earlier listings to _FirstName. Other common naming conventions for the private field that backs a property are _firstName and m_FirstName (a holdover from C++ where the m stands for member variable), as well as the camel case convention, just as with local variables.
Regardless of which naming pattern you use for private fields, the coding standard for public fields and properties is Pascal case. Therefore, public properties should use the LastName and FirstName type patterns. Similarly, if no encapsulating property is created around a public field, Pascal case should be used for the field.
You also can declare properties as static. For example, Listing 5.34 wraps the data for the next ID into a property.
Listing 5.34. Declaring a Static Property
Using Properties with Validation
Notice inside the Employee constructor that you use the property rather than the field for assignment as well. Although not required, the result is that any validation within the property setter will be invoked both inside and outside the class. Consider, for example, what would happen if you changed the LastName property so that it checked value for null or an empty string, before assigning it to _LastName (see Listing 5.35).
Listing 5.35. Providing Property Validation
With this new implementation, the code throws an exception if LastName is assigned an invalid value, either through the constructor or via a direct assignment to LastName from inside Program.Main(). The ability to intercept an assignment and validate the parameters by providing a field-like API is one of the advantages of properties.
It is a good practice to only access a property-backing field from inside the property implementation, to always use the property rather than the field directly. In many cases, this is true even from inside the containing class because that way, when code such as validation code is added, the entire class immediately takes advantage of it. One obvious exception to this occurs when the field is marked as read-only because then the value cannot be set outside of the constructor, even in a property setter.
Although rare, it is possible to assign a value inside the setter, as Listing 5.35 does. In this case, the call to value.Trim() removes any whitespace surrounding the new last name value.
Read-Only and Write-Only Properties
By removing either the getter or the setter portion of a property, you can change a property's accessibility. Properties with only a setter are write-only, which is a relatively rare occurrence. Similarly, providing only a getter will cause the property to be read-only; any attempts to assign a value will cause a compile error. To make Id read-only, for example, you would code it as shown in Listing 5.36.
Listing 5.36. Defining a Read-Only Property
Listing 5.36 assigns the field from within the Employee constructor rather than the property (_Id = id). Assigning via the property causes a compile error, as it does in Program.Main().
Access Modifiers on Getters and Setters
As previously mentioned, it is a good practice not to access fields from outside their properties because doing so circumvents any validation or additional logic that may be inserted. Unfortunately, C# 1.0 did not allow different levels of encapsulation between the getter and setter portions of a property. It was not possible, therefore, to create a public getter and a private setter so that external classes would have read-only access to the property while code within the class could write to the property.
In C# 2.0, support was added for placing an access modifier on either the get or the set portion of the property implementation (not on both), thereby overriding the access modifier specified on the property declaration. Listing 5.37 demonstrates how to do this.
Listing 5.37. Placing Access Modifiers on the Setter
By using private on the setter, the property appears as read-only to classes other than Employee. From within Employee, the property appears as read/write, so you can assign the property within the constructor. When specifying an access modifier on the getter or setter, take care that the access modifier is more restrictive than the access modifier on the property as a whole. It is a compile error, for example, to declare the property as private and the setter as public.
Properties as Virtual Fields
As you have seen, properties behave like virtual fields. In some instances, you do not need a backing field at all. Instead, the property getter returns a calculated value while the setter parses the value and persists it to some other member fields, if at all. Consider, for example, the Name property implementation shown in Listing 5.38. Output 5.6 shows the results.
Listing 5.38. Defining Properties
The getter for the Name property concatenates the values returned from the FirstName and LastName properties. In fact, the name value assigned is not actually stored. When the Name property is assigned, the value on the right side is parsed into its first and last name parts.
Properties and Method Calls Not Allowed as ref or out Parameter Values
C# allows properties to be used identically to fields, except when they are passed as ref or out parameter values. ref and out parameter values are internally implemented by passing the memory address to the target method. However, because properties can be virtual fields that have no backing field, or can be read/write-only, it is not possible to pass the address for the underlying storage. As a result, you cannot pass properties as ref or out parameter values. The same is true for method calls. Instead, when code needs to pass a property or method call as a ref or out parameter value, the code must first copy the value into a variable and then pass the variable. Once the method call has completed, the code must assign the variable back into the property.