Home > Articles > Programming > C#

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

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 5.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 5.16: Declaring Getter and Setter Methods

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. No longer can you 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 type of pattern, the C# designers provided explicit syntax for it. This syntax is called a property (see Listing 5.17 and Output 5.5).

LISTING 5.17: Defining Properties

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

OUTPUT 5.5

Inigo                                                                             

The first thing to notice in Listing 5.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 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, 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.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 5.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.

Automatically Implemented Properties

Begin 3.0

In C# 3.0, property syntax includes a shorthand version. 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 C# 3.0 compiler (and higher) allows the declaration of a property without any accessor implementation or backing field declaration. Listing 5.18 demonstrates the syntax with the Title and Manager properties, and Output 5.6 shows the results.

LISTING 5.18: Automatically Implemented Properties

class Program
{
  static void Main()
  {
        Employee employee1 =
            new Employee();
        Employee employee2 =
            new Employee();
 
        // 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);
  }
}
__________________________________________________________________________________

class Employee
{
  // FirstName property
  public string FirstName
  {
      get
      {
          return _FirstName;
      }
      set
      {
          _FirstName = value;
      }
  }
  private string _FirstName;
 
  // LastName property
  public string LastName
  {
      get
      {
          return _LastName;
      }
      set
      {
          _LastName = value;
      }
  }
  private string _LastName;
 
  public string Title { get; set; }                                               
 
  public Employee Manager { get; set; }                                           
 
  public string Salary { get; set; } = "Not Enough";                              
  // ...
}

OUTPUT 5.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.

End 3.0

Throughout the remainder of the book, we will frequently use this C# 3.0 or later syntax without indicating that it is a feature introduced in C# 3.0.

Begin 6.0

One final thing to note about automatically declared properties is that in C# 6.0, it is possible to initialize them as Listing 5.18 does for Salary:

  public string Salary { get; set; } = "Not Enough";

Prior to C# 6.0, property initialization was possible only via a method (including the constructor, as we discuss later in the chapter). However, with C# 6.0, you can initialize automatically implemented properties at declaration time using a syntax much like that used for field initialization.

End 6.0

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 5.18 the property name is FirstName, and the field name changed from earlier listings to _FirstName—that is, PascalCase with an underscore suffix. 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), and on occasion the camelCase convention, just like with local variables.3 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 or protected.

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, that the property name is the same as the type name. Consider an Address property of type Address on a Person object, for example.

Using Properties with Validation

Notice in Listing 5.19 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.

LISTING 5.19: Providing Property Validation

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
      {
          return _LastName;
      }
      set
      {
          // Validate LastName assignment                                
          if(value == null)                                              
          {                                                              
              // Report error                                            
              // In C# 6.0 replace "value" with nameof(value)            
              throw new ArgumentNullException("value");                  
          }                                                              
          else                                                           
          {                                                              
              // Remove any whitespace around                            
              // the new last name.                                      
              value = value.Trim();                                      
              if(value == "")                                            
              {                                                          
                  // Report error                                        
                  // In C# 6.0 replace "value" with nameof(value)        
                  throw new ArgumentException(                           
                      "LastName cannot be blank.", "value");4            
              }                                                          
              else                                                       
                  _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 5.19 does. In this case, the call to value.Trim() removes any whitespace surrounding the new last name value.

Begin 6.0
End 6.0

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

LISTING 5.20: Defining a Read-Only Property prior to C# 6.0

class Program
{
  static void Main()
  {
      Employee employee1 = new Employee();
      employee1.Initialize(42);
 
      // ERROR:  Property or indexer 'Employee.Id'                                  
      // cannot be assigned to; it is read-only.                                    
      // employee1.Id = "490";                                                      
  }
}
 
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
      {
          return _Id;
      }
      // No setter provided.                                                         
  }
  private string _Id;
 
}

Listing 5.20 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().

Begin 6.0

Starting in C# 6.0, there is also support for read-only automatically implemented properties as follows:

      public bool[,,] Cells { get; } = new bool[2, 3, 3];

This is clearly a significant improvement over the pre-C# 6.0 approach, especially given the commonality of read-only properties for something like an array of items or the Id in Listing 5.20.

One important note about a read-only automatically implemented property is that, like read-only fields, the compiler requires that it be initialized in the constructor or via an initializer. In the preceding snippet we use an initializer, but the assignment of Cells from within the constructor is also permitted.

Given the guideline that fields should not be accessed from outside their wrapping property, those programming in a C# 6.0 world will discover that there is virtually no need to ever use pre-C# 6.0 syntax; instead, the programmer can always 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.

End 6.0

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 it even exists). Consider, for example, the Name property implementation shown in Listing 5.21. Output 5.7 shows the results.

LISTING 5.21: Defining Properties

class Program
{
  static void Main()
  {
      Employee employee1 = new Employee();

      employee1.Name = "Inigo Montoya";                                           
      System.Console.WriteLine(employee1.Name);                                   

      // ...
  }
}
__________________________________________________________________________________
class Employee
{
  // ...

  // FirstName property
  public string FirstName
  {
      get
      {
          return _FirstName;
      }
      set
      {
          _FirstName = value;
      }
  }
  private string _FirstName;

  // LastName property
  public string LastName
  {
      get
      {
          return _LastName;
      }
      set
      {
          _LastName = value;
      }
  }
  private string _LastName;
  // ...

  // Name property                                                                
  public string Name                                                              
  {                                                                               
      get                                                                         
      {                                                                           
          return $"{ FirstName } { LastName }";                                   
      }                                                                           
      set                                                                         
      {                                                                           
          // 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", "value");             
          }                                                                       
      }                                                                           
  }
  public string Initials => $"{ FirstName[0] } { LastName[0] }";
  // ...
}

OUTPUT 5.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

Begin 2.0

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.22 demonstrates how to do this.

LISTING 5.22: Placing Access Modifiers on the Setter

class Program
{
  static void Main()
  {
      Employee employee1 = new Employee();
      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";                                                       
  }
}
__________________________________________________________________________________

class Employee
{
  public void Initialize(int id)
  {
      // Set Id property                                                          
      Id = id.ToString();                                                         
  }
 
  // ...
  // Id property declaration
  public string Id
  {
      get
      {
          return _Id;
      }
      // Providing an access modifier is possible in C# 2.0
      // and higher only
      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 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.

End 2.0

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

  • + Share This
  • 🔖 Save To Your Account