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
public class Employee
{
    public string FirstName;
    public string LastName;
    public string? Salary;
    // Working de-crypted passwords for elucidation only
    // this is not recommended.
    // Uninitialized; pending explanation of constructors
    private string Password;  
    private bool IsAuthenticated;
 
    public bool Logon(string password)
    {
        if(Password == password)
        {
            IsAuthenticated = true;
        }
        return IsAuthenticated;
    }
 
    public bool GetIsAuthenticated()
    {
        return IsAuthenticated;
    }
    // ...
}
 
public class Program
{
    public static void Main()
    {
        Employee employee = new();
 
        employee.FirstName = "Inigo";
        employee.LastName = "Montoya";
 
        // ...
 
        
        // ERROR: Password is private, so it cannot be
        // accessed from outside the class
        Console.WriteLine(
           "Password = {0}", employee.Password);
    }
    // ...
}

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
public class Employee
{
    private string FirstName;
    // FirstName getter
    public string GetFirstName()
    {
        return FirstName;
    }
    // FirstName setter
    public void SetFirstName(string newFirstName)
    {
        if(newFirstName != null && newFirstName != "")
        {
            FirstName = newFirstName;
        }
    }
 
    private string LastName;
    // LastName getter
    public string GetLastName()
    {
        return LastName;
    }
    // LastName setter
    public void SetLastName(string newLastName)
    {
        if(newLastName != null && newLastName != "")
        {
            LastName = newLastName;
        }
    }
    // ...
}

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
public class Program
{
    public static void Main()
    {
        Employee employee = new();
 
        // Call the FirstName property's setter
        employee.FirstName = "Inigo";
 
        // Call the FirstName property's getter
        System.Console.WriteLine(employee.FirstName);
    }
}
 
public class Employee
{
    // FirstName property
    public string FirstName
    {
        get
        {
            return _FirstName;
        }
        set
        {
            _FirstName = value;
        }
    }
    private string _FirstName;
 
    // ...
}
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
public class Employee
{
    // FirstName property
    public string FirstName
    {
        get
        {
            return _FirstName;
        }
        set
        {
            _FirstName = value;
        }
    }
    private string _FirstName;
    // LastName property
    public string LastName
    {
        get => _LastName;
        set => _LastName = value;
    }
    private string _LastName;
    // ...
}

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
public class Program
{
    public static void Main()
    {
        Employee employee1 =
            new();
        Employee employee2 =
            new();
 
        // Call the FirstName property's setter
        employee1.FirstName = "Inigo";
 
        // Call the FirstName property's getter
        System.Console.WriteLine(employee1.FirstName);
 
        // Assign an auto-implemented property
        employee2.Title = "Computer Nerd";
        employee1.Manager = employee2;
 
        // Print employee1's manager's title
        System.Console.WriteLine(employee1.Manager.Title);
    }
}
 
public class Employee
{
    // FirstName property
    public string FirstName
    {
        get
        {
            return _FirstName;
        }
        set
        {
            _FirstName = value;
        }
    }
    private string _FirstName;
 
    // LastName property
    public string LastName
    {
        get => _LastName;
        set => _LastName = value;
    }
    private string _LastName;
 
    // Title property
    public string? Title { getset; }
 
    // Manager property
    public Employee? Manager { getset; }
 
    public string? Salary { getset; } = "Not Enough";
    // ...
}
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
public class Employee
{
    // ...
    public void Initialize(
        string newFirstName, string newLastName)
    {
        // Use property inside the Employee
        // class as well
        FirstName = newFirstName;
        LastName = newLastName;
    }
 
    // LastName property
    public string LastName
    {
        get => _LastName;
        set
        {
            // ...
            // Validate LastName assignment
            
            ArgumentException.ThrowIfNullOrEmpty(value = value?.Trim()!);
            // ...
            _LastName = value;
        }
    }
    private string _LastName;
// ...
}

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
public class Program
{
    public static void Main()
    {
        Employee employee1 = new();
        employee1.Initialize(42);
 
        // ERROR:  Property or indexer 'Employee.Id' 
        // cannot be assigned to; it is read-only
        employee1.Id = "490";
    }
}
 
public class Employee
{
    public void Initialize(int id)
    {
        // Use field because Id property has no setter;
        // it is read-only
        _Id = id.ToString();
    }
 
    // ...
    // Id property declaration
    public string Id
    {
        get => _Id;
        // No setter provided
    }
    private string _Id;
}

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
public class Program
{
    public static void Main()
    {
        Employee employee1 = new();
 
        employee1.Name = "Inigo Montoya";
        System.Console.WriteLine(employee1.Name);
 
        // ...
    }
}
 
public class Employee
{
    // ...
 
    // FirstName property
    public string FirstName
    {
        get
        {
            return _FirstName;
        }
        set
        {
            _FirstName = value;
        }
    }
    private string _FirstName;
 
    // LastName property
    public string LastName
    {
        get => _LastName;
        set => _LastName = value;
    }
    private string _LastName;
    // ...
 
    // Name property
    public string Name
    {
        get
        {
            return $"{ FirstName } { LastName }";
        }
        set
        {
            // ...
            ArgumentException.ThrowIfNullOrEmpty(value = value?.Trim()!);
            // ...
            // Split the assigned value into 
            // first and last names
            string[] names;
            names = value.Split(new char[] { ' ' });
            if(names.Length == 2)
            {
                FirstName = names[0];
                LastName = names[1];
            }
            else
            {
                // Throw an exception if the full 
                // name was not assigned
                throw new System.ArgumentException(
                    $"Assigned value 'value }' is invalid",
                    nameof(value));
            }
        }
    }
 
    public string Initials => $"{ FirstName[0] } { LastName[0] }";
    // ...
}
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
public class Program
{
    public static void Main()
    {
        Employee employee1 = new();
        employee1.Initialize(42);
        // ERROR: The property or indexer 'Employee.Id' 
        // cannot be used in this context because the set 
        // accessor is inaccessible
        employee1.Id = "490";
    }
}
 
public class Employee
{
    public void Initialize(int id)
    {
        // Set Id property
        Id = id.ToString();
    }
 
    // ...
    // Id property declaration
    public string Id
    {
        get => _Id;
        private set => _Id = value;
    }
    private string _Id;
}

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
// ...
 
.field private string _FirstName
.method public hidebysig specialname instance string
        get_FirstName() cil managed
    {
        // Code size       12 (0xc)
        .maxstack  1
        .locals init (string V_0)
        IL_0000:  nop
        IL_0001:  ldarg.0
        IL_0002:  ldfld      string Employee::_FirstName
        IL_0007:  stloc.0
        IL_0008:  br.s IL_000a
 
        IL_000a:  ldloc.0
        IL_000b:  ret
    } // End of method Employee::get_FirstName
 
    .method public hidebysig specialname instance void
            set_FirstName(string 'value') cil managed
    {
      // Code size       9 (0x9)
      .maxstack  8
      IL_0000:  nop
      IL_0001:  ldarg.0
      IL_0002:  ldarg.1
      IL_0003:  stfld      string Employee::_FirstName
      IL_0008:  ret
    } // End of method Employee::set_FirstName
 
    .property instance string FirstName()
    {
      .get instance string Employee::get_FirstName()
      .set instance void Employee::set_FirstName(string)
    } // End of property Employee::FirstName
 
    // ...

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
.property instance string FirstName()
{
  .get instance string Program::get_FirstName()
  .set instance void Program::set_FirstName(string)
// 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 }}
;