When declaring a field earlier in the chapter, you prefixed the field declaration with the keyword public. public is an access modifier that identifies the level of encapsulation associated with the member it decorates. Seven access modifiers are available: public, private, protected, internal, protected internal, private protected, and file. This section considers the first two.
Besides wrapping data and methods together into a single unit, encapsulation deals with hiding the internal details of an object’s data and behavior. To some degree, methods do this; from outside a method, all that is visible to a caller is the method declaration. None of the internal implementation is visible. Object-oriented programming enables this further, however, by providing facilities for controlling the extent to which members are visible from outside the class. Members that are not visible outside the class are private members.
In object-oriented programming, encapsulation is a term meaning not only grouping data and behavior, but also hiding data and behavior implementation details within a class (the capsule) so that the inner workings of a class are not exposed. This reduces the chance that callers will modify the data inappropriately or program according to the implementation, only to have it change in the future.
The purpose of an access modifier is to provide encapsulation. By using public, you explicitly indicate that it is acceptable that the modified fields are accessible from outside the Employee class—that they are accessible from the Program class, for example.
But consider an Employee class that includes a Password field. It should be possible to call an Employee object and verify the password using a Logon() method. Conversely, it should not be possible to access the Password field on an Employee object from outside the class.
To define a Password field as hidden and inaccessible from outside the containing class, you use the keyword private for the access modifier, in place of public (see Listing 6.15). As a result, the Password field is only accessible from inside the Employee class, for example.
Although this option is not shown in Listing 6.15, it is possible to decorate a method with an access modifier of private as well.
If no access modifier is placed on a class member, the declaration defaults to private. In other words, members are private by default and programmers need to specify explicitly that a member is to be public.
The preceding section, “Access Modifiers,” 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 strict, 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. In yet another scenario, perhaps you 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 6.16 changes both FirstName and LastName to private fields. Public getter and setter methods for each field allow their values to be accessed and changed.
Unfortunately, this change affects the programmability of the Employee class. You can no longer use the assignment operator to set data within the class, nor can you access the data without calling a method.
Recognizing the frequency of this pattern, the C# designers provided explicit syntax for it. This syntax is called a property (see Listing 6.17 and Output 6.5).
The first thing to notice in Listing 6.17 is not the property code itself, but rather 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 syntax 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 a syntax that looks programmatically like a field. In actuality, 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 6.16. 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 6.17’s property implementations are the most commonly used. When the getter is called (such as in Console.WriteLine(employee.FirstName)), the value from the field (_FirstName) is obtained and written to the console.
It is also possible to declare property getters and setters using expression bodied members,1 as shown in Listing 6.18.
Listing 6.18 uses two different syntaxes for an identical property implementation. In real-world code, you should try to be consistent in your choice of syntax.
Since a property with a single backing field that is assigned and retrieved by the get and set accessors is so trivial and common (see the implementations of FirstName and LastName), the compiler allows the declaration of a property without any accessor implementation or backing field declaration.2 Listing 6.19 demonstrates the syntax with the Title and Manager properties, and Output 6.6 shows the results.
Auto-implemented properties provide for a simpler way of writing properties in addition to reading them. Furthermore, when it comes time to add something such as validation to the setter, any existing code that calls the property will not have to change, even though the property declaration will have changed to include an implementation.
One final thing to note about automatically declared properties is that it is possible to initialize them3 as Listing 6.19 does for Salary:
public string? Salary { get; set; } = "Not Enough";
Automatically implemented property initialization (auto-property initialization) using declaration syntax is much like that used for field initialization.
Given that it is possible to write explicit setter and getter methods rather than properties, on occasion a question may arise as to whether it is better to use a property or a method. The general guideline is that methods should represent actions and properties should represent data. Properties are intended to provide simple access to simple data with a simple computation. The expectation is that invoking a property will not be significantly more expensive than accessing a field.
With regard to naming, notice that in Listing 6.19 the property name is FirstName, and the field name changed from earlier listings to _FirstName—that is, PascalCase with an underscore prefix. Other common naming conventions for the private field that backs a property are _firstName and, on occasion, the camelCase convention, just like with local variables.4 The camelCase convention should be avoided, however. The camelCase used for property names is the same as the naming convention used for local variables and parameters, meaning that overlaps in names become highly probable. Also, to respect the principles of encapsulation, fields should not be declared as public.
Regardless of which naming pattern you use for private fields, the coding standard for properties is PascalCase. Therefore, properties should use the LastName and FirstName pattern with names that represent nouns, noun phrases, or adjectives. It is not uncommon, in fact, for the property name to be the same as the type name. Consider an Address property of type Address on a Person object, for example.
Notice in Listing 6.20 that the Initialize() method of Employee uses the property rather than the field for assignment as well. Although this is 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. (Recall checking for null is necessary because even though the data type is a non-nullable string, the caller may have nullable reference types disabled, or the method may be invoked from C# 7.0 or earlier—before nullable reference types existed.)
With this new implementation, the code throws an exception if LastName is assigned an invalid value, either from another member of the same class 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 access a property-backing field only from inside the property implementation. In other words, you should always use the property rather than calling the field directly. In many cases, this principle holds even from code within the same class as the property. If you follow this practice, when you add code such as validation code, the entire class immediately takes advantage of it.5
Although rare, it is possible to assign value inside the setter, as Listing 6.20 does. In this case, the call to value.Trim() removes any whitespace surrounding the new last name value.
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 use the code shown in Listing 6.21.
Listing 6.21 assigns the field from within the Employee Initialize() method rather than the property (_Id = id). Assigning via the property causes a compile error, as it does in Program.Main().
There is also support for read-only, automatically implemented properties,6 as follows:
public bool[] Cells { get; } = new bool[9];
One important note about a read-only automatically implemented property is that, like read-only fields, the compiler requires that such a property be initialized via an auto-property initializer (or in the constructor). In the preceding snippet we use an initializer, but the assignment of Cells from within the constructor is also permitted, as we shall see shortly.
Given the guideline that fields should not be accessed from outside their wrapping property, the programmer should instead use a read-only, automatically implemented property. The only exception might be when the data type of the read-only modified field does not match the data type of the property—for example, if the field was of type int and the read-only property was of type double.
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 it even exists). Consider, for example, the Name property implementation shown in Listing 6.22. Output 6.7 shows the results.
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.
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.
An access modifier can appear on either the get or the set portion of the property implementation7 (not on both), thereby overriding the access modifier specified on the property declaration. Listing 6.23 demonstrates how to do this.
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 class itself. 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.
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 may not have a backing field or can be read-only or 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.
Listing 6.24 shows that getters and setters are exposed as get_FirstName() and set_FirstName() in the Common Intermediate Language (CIL).
Just as important to their appearance as regular methods is the fact that properties are an explicit construct within the CIL, too. As Listing 6.25 shows, the getters and setters are called by CIL properties, which are an explicit construct within the CIL code. Because of this, languages and compilers are not restricted to always interpreting properties based on a naming convention. Instead, CIL properties provide a means for compilers and code editors to provide special syntax.
Notice in Listing 6.24 that the getters and setters that are part of the property include the specialname metadata. This modifier is what IDEs, such as Visual Studio, use as a flag to hide the members from IntelliSense.
An automatically implemented property is almost identical to one for which you define the backing field explicitly. In place of the manually defined backing field, the C# compiler generates a field with the name <PropertyName>k_BackingField in CIL. This generated field includes an attribute (see Chapter 18) called System.Runtime.CompilerServices.CompilerGeneratedAttribute. Both the getters and the setters are decorated with the same attribute because they, too, are generated—with the same implementation as in Listings 5.23 and 5.24.
________________________________________