Access Modifiers

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.

Beginner Topic
Encapsulation Part 2: Information Hiding

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.

Listing 6.15: Using the private Access Modifier
1. public class Employee
2. {
3.     public string FirstName;
4.     public string LastName;
5.     public string? Salary;
6.     // Working de-crypted passwords for elucidation only
7.     // this is not recommended.
8.     // Uninitialized; pending explanation of constructors
9.     private string Password;  
10.     private bool IsAuthenticated;
11.  
12.     public bool Logon(string password)
13.     {
14.         if(Password == password)
15.         {
16.             IsAuthenticated = true;
17.         }
18.         return IsAuthenticated;
19.     }
20.  
21.     public bool GetIsAuthenticated()
22.     {
23.         return IsAuthenticated;
24.     }
25.     // ...
26. }
27.  
28. public class Program
29. {
30.     public static void Main()
31.     {
32.         Employee employee = new();
33.  
34.         employee.FirstName = "Inigo";
35.         employee.LastName = "Montoya";
36.  
37.         // ...
38.  
39.         
40.         // ERROR: Password is private, so it cannot be
41.         // accessed from outside the class
42.         Console.WriteLine(
43.            "Password = {0}", employee.Password);
44.     }
45.     // ...
46. }

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.

Properties

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.

Listing 6.16: Declaring Getter and Setter Methods
1. public class Employee
2. {
3.     private string FirstName;
4.     // FirstName getter
5.     public string GetFirstName()
6.     {
7.         return FirstName;
8.     }
9.     // FirstName setter
10.     public void SetFirstName(string newFirstName)
11.     {
12.         if(newFirstName != null && newFirstName != "")
13.         {
14.             FirstName = newFirstName;
15.         }
16.     }
17.  
18.     private string LastName;
19.     // LastName getter
20.     public string GetLastName()
21.     {
22.         return LastName;
23.     }
24.     // LastName setter
25.     public void SetLastName(string newLastName)
26.     {
27.         if(newLastName != null && newLastName != "")
28.         {
29.             LastName = newLastName;
30.         }
31.     }
32.     // ...
33. }

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.

Declaring a Property

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).

Listing 6.17: Defining Properties
1. public class Program
2. {
3.     public static void Main()
4.     {
5.         Employee employee = new();
6.  
7.         // Call the FirstName property's setter
8.         employee.FirstName = "Inigo";
9.  
10.         // Call the FirstName property's getter
11.         System.Console.WriteLine(employee.FirstName);
12.     }
13. }
14.  
15. public class Employee
16. {
17.     // FirstName property
18.     public string FirstName
19.     {
20.         get
21.         {
22.             return _FirstName;
23.         }
24.         set
25.         {
26.             _FirstName = value;
27.         }
28.     }
29.     private string _FirstName;
30.  
31.     // ...
32. }
Output 6.5
Inigo

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: Defining Properties with Expression Bodied Members
1. public class Employee
2. {
3.     // FirstName property
4.     public string FirstName
5.     {
6.         get
7.         {
8.             return _FirstName;
9.         }
10.         set
11.         {
12.             _FirstName = value;
13.         }
14.     }
15.     private string _FirstName;
16.     // LastName property
17.     public string LastName
18.     {
19.         get => _LastName;
20.         set => _LastName = value;
21.     }
22.     private string _LastName;
23.     // ...
24. }

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.

Automatically Implemented Properties

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.

Listing 6.19: Automatically Implemented Properties
1. public class Program
2. {
3.     public static void Main()
4.     {
5.         Employee employee1 =
6.             new();
7.         Employee employee2 =
8.             new();
9.  
10.         // Call the FirstName property's setter
11.         employee1.FirstName = "Inigo";
12.  
13.         // Call the FirstName property's getter
14.         System.Console.WriteLine(employee1.FirstName);
15.  
16.         // Assign an auto-implemented property
17.         employee2.Title = "Computer Nerd";
18.         employee1.Manager = employee2;
19.  
20.         // Print employee1's manager's title
21.         System.Console.WriteLine(employee1.Manager.Title);
22.     }
23. }
24.  
25. public class Employee
26. {
27.     // FirstName property
28.     public string FirstName
29.     {
30.         get
31.         {
32.             return _FirstName;
33.         }
34.         set
35.         {
36.             _FirstName = value;
37.         }
38.     }
39.     private string _FirstName;
40.  
41.     // LastName property
42.     public string LastName
43.     {
44.         get => _LastName;
45.         set => _LastName = value;
46.     }
47.     private string _LastName;
48.  
49.     // Title property
50.     public string? Title { getset; }
51.  
52.     // Manager property
53.     public Employee? Manager { getset; }
54.  
55.     public string? Salary { getset; } = "Not Enough";
56.     // ...
57. }
Output 6.6
Inigo
Computer Nerd

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.

Property and Field Guidelines

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.

Guidelines
DO use properties for simple access to simple data with simple computations.
AVOID throwing exceptions from property getters.
DO preserve the original property value if the property throws an exception.
CONSIDER using the same casing on a property’s backing field as that used in the property, distinguishing the backing field with an “_” prefix.
DO name properties using a noun, noun phrase, or adjective.
CONSIDER giving a property the same name as its type.
AVOID naming fields with camelCase.
DO favor prefixing Boolean properties with “Is,” “Can,” or “Has,” when that practice adds value.
DO declare all instance fields as private (and expose them via a property).
DO name properties with PascalCase.
DO favor automatically implemented properties over fields.
DO favor automatically implemented properties over using fully expanded ones if there is no additional implementation logic.
Using Properties with Validation

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.)

Listing 6.20: Providing Property Validation
1. public class Employee
2. {
3.     // ...
4.     public void Initialize(
5.         string newFirstName, string newLastName)
6.     {
7.         // Use property inside the Employee
8.         // class as well
9.         FirstName = newFirstName;
10.         LastName = newLastName;
11.     }
12.  
13.     // LastName property
14.     public string LastName
15.     {
16.         get => _LastName;
17.         set
18.         {
19.             // ...
20.             // Validate LastName assignment
21.             
22.             ArgumentException.ThrowIfNullOrEmpty(value = value?.Trim()!);
23.             // ...
24.             _LastName = value;
25.         }
26.     }
27.     private string _LastName;
28. // ...
29. }

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.

Guidelines
AVOID accessing the backing field of a property outside the property, even from within the containing class.
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 use the code shown in Listing 6.21.

Listing 6.21: Defining a Read-Only Property Prior to C# 6.0
1. public class Program
2. {
3.     public static void Main()
4.     {
5.         Employee employee1 = new();
6.         employee1.Initialize(42);
7.  
8.         // ERROR:  Property or indexer 'Employee.Id' 
9.         // cannot be assigned to; it is read-only
10.         employee1.Id = "490";
11.     }
12. }
13.  
14. public class Employee
15. {
16.     public void Initialize(int id)
17.     {
18.         // Use field because Id property has no setter;
19.         // it is read-only
20.         _Id = id.ToString();
21.     }
22.  
23.     // ...
24.     // Id property declaration
25.     public string Id
26.     {
27.         get => _Id;
28.         // No setter provided
29.     }
30.     private string _Id;
31. }

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.

Guidelines
DO create read-only properties if the property value should not be changed.
DO create read-only automatically implemented properties, rather than read-only properties with a backing field if the property value should not be changed.
Calculated Properties

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.

Listing 6.22: Defining Calculated Properties
1. public class Program
2. {
3.     public static void Main()
4.     {
5.         Employee employee1 = new();
6.  
7.         employee1.Name = "Inigo Montoya";
8.         System.Console.WriteLine(employee1.Name);
9.  
10.         // ...
11.     }
12. }
13.  
14. public class Employee
15. {
16.     // ...
17.  
18.     // FirstName property
19.     public string FirstName
20.     {
21.         get
22.         {
23.             return _FirstName;
24.         }
25.         set
26.         {
27.             _FirstName = value;
28.         }
29.     }
30.     private string _FirstName;
31.  
32.     // LastName property
33.     public string LastName
34.     {
35.         get => _LastName;
36.         set => _LastName = value;
37.     }
38.     private string _LastName;
39.     // ...
40.  
41.     // Name property
42.     public string Name
43.     {
44.         get
45.         {
46.             return $"{ FirstName } { LastName }";
47.         }
48.         set
49.         {
50.             // ...
51.             ArgumentException.ThrowIfNullOrEmpty(value = value?.Trim()!);
52.             // ...
53.             // Split the assigned value into 
54.             // first and last names
55.             string[] names;
56.             names = value.Split(new char[] { ' ' });
57.             if(names.Length == 2)
58.             {
59.                 FirstName = names[0];
60.                 LastName = names[1];
61.             }
62.             else
63.             {
64.                 // Throw an exception if the full 
65.                 // name was not assigned
66.                 throw new System.ArgumentException(
67.                     $"Assigned value 'value }' is invalid",
68.                     nameof(value));
69.             }
70.         }
71.     }
72.  
73.     public string Initials => $"{ FirstName[0] } { LastName[0] }";
74.     // ...
75. }
Output 6.7
Inigo Montoya

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.

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.

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.

Listing 6.23: Placing Access Modifiers on the Setter
1. public class Program
2. {
3.     public static void Main()
4.     {
5.         Employee employee1 = new();
6.         employee1.Initialize(42);
7.         // ERROR: The property or indexer 'Employee.Id' 
8.         // cannot be used in this context because the set 
9.         // accessor is inaccessible
10.         employee1.Id = "490";
11.     }
12. }
13.  
14. public class Employee
15. {
16.     public void Initialize(int id)
17.     {
18.         // Set Id property
19.         Id = id.ToString();
20.     }
21.  
22.     // ...
23.     // Id property declaration
24.     public string Id
25.     {
26.         get => _Id;
27.         private set => _Id = value;
28.     }
29.     private string _Id;
30. }

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.

Guidelines
DO apply appropriate accessibility modifiers on implementations of getters and setters on all properties.
DO NOT provide set-only properties or properties with the setter having broader accessibility than the getter.
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 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.

AdVanced Topic
Property Internals

Listing 6.24 shows that getters and setters are exposed as get_FirstName() and set_FirstName() in the Common Intermediate Language (CIL).

Listing 6.24: CIL Code Resulting from Properties
1. // ...
2.  
3. .field private string _FirstName
4. .method public hidebysig specialname instance string
5.         get_FirstName() cil managed
6.     {
7.         // Code size       12 (0xc)
8.         .maxstack  1
9.         .locals init (string V_0)
10.         IL_0000:  nop
11.         IL_0001:  ldarg.0
12.         IL_0002:  ldfld      string Employee::_FirstName
13.         IL_0007:  stloc.0
14.         IL_0008:  br.s IL_000a
15.  
16.         IL_000a:  ldloc.0
17.         IL_000b:  ret
18.     } // End of method Employee::get_FirstName
19.  
20.     .method public hidebysig specialname instance void
21.             set_FirstName(string 'value') cil managed
22.     {
23.       // Code size       9 (0x9)
24.       .maxstack  8
25.       IL_0000:  nop
26.       IL_0001:  ldarg.0
27.       IL_0002:  ldarg.1
28.       IL_0003:  stfld      string Employee::_FirstName
29.       IL_0008:  ret
30.     } // End of method Employee::set_FirstName
31.  
32.     .property instance string FirstName()
33.     {
34.       .get instance string Employee::get_FirstName()
35.       .set instance void Employee::set_FirstName(string)
36.     } // End of property Employee::FirstName
37.  
38.     // ...

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.

Listing 6.25: Properties Are an Explicit Construct in CIL
1. .property instance string FirstName()
2. {
3.   .get instance string Program::get_FirstName()
4.   .set instance void Program::set_FirstName(string)
5.// End of property Program::FirstName

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.

________________________________________

1. Starting with C# 7.0.
2. Introduced in C# 3.0.
3. Starting in C# 6.0.
4. We prefer _FirstName because the m in front of the name is unnecessary when compared with an underscore (_). Also, by using the same casing as the property, it is possible to have only one string within the Visual Studio code template expansion tools instead of having one for both the property name and the field name.
5. As described later in the chapter, one exception to this occurs when the field is marked as read-only, because then the value can be set only in the constructor. In C# 6.0, you can directly assign the value of a read-only property, completely eliminating the need for the read-only field.
6. Starting in C# 6.0.
7. Introduced in C# 2.0. 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.
{{ snackbarMessage }}
;