Properties




Properties

The Access Modifiers section, earlier in this chapter, demonstrated how you can use the private keyword to encapsulate a password, preventing access from outside the class. This type of encapsulation is often too thorough, however. For example, sometimes you might need to define fields that external classes can only read but whose values you can change internally. Alternatively, perhaps you want to allow access to write some data in a class but you need to be able to validate changes made to the data. Still one more example is the need to construct the data on the fly.

Traditionally, languages enabled the features found in these examples by marking fields as private and then providing getter and setter methods for accessing and modifying the data. The code in Listing 5.30 changes both FirstName and LastName to private fields. Public getter and setter methods for each field allow their values to be accessed and changed.

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()
  {
      returnLastName;
  }
  // 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 data without calling a method.

Declaring a Property

Considering the frequency of this type of pattern, the C# designers decided to provide explicit syntax for it. This syntax is called a property (see Listing 5.31 and Output 5.5).

Defining Properties

class Program
{
  static void Main()
  {
      Employee employee = new Employee("Domingo", "Montoya");
      // Call the FirstName property's setter.
      employee.FirstName = "Inigo";

      // Call the FirstName property's getter.
      Console.WriteLine(employee.FirstName);
  }
}

class Employee
{
  public Employee(string newFirstName, string newLastName)
  {
      // Use property inside the Employee
      // class as well.
      FirstName = newFirstName;
      LastName = newLastName;
  }

   // 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.31 is not the property code itself, but the code within the Program class. Although you no longer have the fields with the FirstName and LastName identifiers, you cannot see this by looking at the Program class. The API for accessing an employee's first and last names has not changed at all. It is still possible to assign the parts of the name using a simple assignment operator, for example (employee.FirstName = "Inigo").

The key feature is that properties provide an API that looks programmatically like a field. In actuality, however, no such fields exist. A property declaration looks exactly like a field declaration, but following it are curly braces in which to place the property implementation. Two optional parts make up the property implementation. The get part defines the getter portion of the property. It corresponds directly to the GetFirstName() and GetLastName() functions defined in Listing 5.30. To access the FirstName property you call employee.FirstName. Similarly, setters (the set portion of the implementation) enable the calling syntax of the field assignment:

 employee.FirstName = "Inigo";

Property definition syntax uses three contextual keywords. You use the get and set keywords to identify either the retrieval or the assignment portion of the property, respectively. In addition, the setter uses the value keyword to refer to the right side of the assignment operation. When Program.Main() calls employee.FirstName = "Inigo", therefore, value is set to "Inigo" inside the setter and can be used to assign _FirstName. Listing 5.31's property implementations are the most common. When the getter is called (such as in Console.WriteLine(employee2.FirstName)), the value from the field (_FirstName) is returned.

Advanced Topic: Property Internals

Listing 5.32 shows that getters and setters are exposed as get_FirstName() and set_FirstName() in the CIL.

CIL Code Resulting from Properties

.method public hidebysig specialname instance string
        get_FirstName() cil managed
{
   // Code size       12 (0xc)
   .maxstack1
   .locals init ([0] string CS$1$0000)
   IL_0000:  nop
   IL_0001: ldarg.0

   IL_0002: ldfld      string TicTacToe.Program::_FirstName
   IL_0007: stloc.0
   IL_0008: br.s       IL_000a
   IL_000a: ldloc.0
   IL_000b: ret
} // end of method Program:: get_FirstName

.method public hidebysig specialname instance void
        get_FirstName(string 'value') cil managed
{
   // Code size         9 (0x9)
   .maxstack8
   IL_0000: nop
   IL_0001: ldarg.0
   IL_0002: ldarg.1
   IL_0003: stfld       string TicTacToe.Program::_FirstName
   IL_0008: ret
} // end of method Program::set_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 5.33 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.

Properties Are an Explicit Construct in CIL

.property instance string FirstName()
{
  .get instance string TicTacToe.Program::get_FirstName()
  .set instance void TicTacToe.Program::set_FirstName(string)
} // end of property Program::FirstName

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


Naming Conventions

Because the property name is FirstName, the field name changed from earlier listings to _FirstName. Other common naming conventions for the private field that backs a property are _firstName and m_FirstName (a holdover from C++ where the m stands for member variable), as well as the camel case convention, just as with local variables.[1]

[1] I prefer _FirstName because the m in front of the name is unnecessary when compared with simply _, and 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.

Regardless of which naming pattern you use for private fields, the coding standard for public fields and properties is Pascal case. Therefore, public properties should use the LastName and FirstName type patterns. Similarly, if no encapsulating property is created around a public field, Pascal case should be used for the field.

Static Properties

You also can declare properties as static. For example, Listing 5.34 wraps the data for the next ID into a property.

Declaring a Static Property

class Employee
{
   // ...
   public static int NextId                                               
   {                                                                      
       get                                                                
       {                                                                  
          return _NextId;                                                 
       }                                                                  
       private set                                                        
       {                                                                  
          _NextId = value;                                                
       }                                                                  
   }                                                                      
   public static int _NextId = 42;                                        
   // ...
}

Using Properties with Validation

Notice inside the Employee constructor that you use the property rather than the field for assignment as well. Although not required, the result is that any validation within the property setter will be invoked both inside and outside the class. Consider, for example, what would happen if you changed the LastName property so that it checked value for null or an empty string, before assigning it to _LastName (see Listing 5.35).

Providing Property Validation

class Employee
{
   // ...
   // LastName property
   public string LastName
   {
       get
       {
           return _LastName;
       }
       set
       {
           // Validate LastName assignment                                 
           if(value == null)                                               
          {                                                                
               // Report error                                            
                throw new NullReferenceException();                         
           }                                                               
           else                                                            
           {                                                               
               // Remove any whitespace around                             
               // the new last name.                                       
               value = value.Trim();                                       
               if(value == "")                                             
               {                                                           
                   throw new ApplicationException(                         
                       "LastName cannot be blank.");                       
               }                                                           
               else                                                        
                  _LastName = value;                                       
           }                                                                
       }
   }
   private string _LastName;
   // ...
}

With this new implementation, the code throws an exception if LastName is assigned an invalid value, either through the constructor or via a direct assignment to LastName from inside Program.Main(). The ability to intercept an assignment and validate the parameters by providing a field-like API is one of the advantages of properties.

It is a good practice to only access a property-backing field from inside the property implementation, to always use the property rather than the field directly. In many cases, this is true even from inside the containing class because that way, when code such as validation code is added, the entire class immediately takes advantage of it. One obvious exception to this occurs when the field is marked as read-only because then the value cannot be set outside of the constructor, even in a property setter.

Although rare, it is possible to assign a value inside the setter, as Listing 5.35 does. In this case, the call to value.Trim() removes any whitespace surrounding the new last name value.

Read-Only and Write-Only Properties

By removing either the getter or the setter portion of a property, you can change a property's accessibility. Properties with only a setter are write-only, which is a relatively rare occurrence. Similarly, providing only a getter will cause the property to be read-only; any attempts to assign a value will cause a compile error. To make Id read-only, for example, you would code it as shown in Listing 5.36.

Defining a Read-Only Property

class Program
{
  static void Main()
  {
      Employee employee1 = new Employee(42);
      // ERROR:Id is read-only                                           
      // Employee.Id = 490;                                              
  }
}

class Employee
{
  public Employee(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.36 assigns the field from within the Employee constructor rather than the property (_Id = id). Assigning via the property causes a compile error, as it does in Program.Main().

Access Modifiers on Getters and Setters

As previously mentioned, it is a good practice not to access fields from outside their properties because doing so circumvents any validation or additional logic that may be inserted. Unfortunately, C# 1.0 did not allow different levels of encapsulation between the getter and setter portions of a property. It was not possible, therefore, to create a public getter and a private setter so that external classes would have read-only access to the property while code within the class could write to the property.

In C# 2.0, support was added for placing an access modifier on either the get or the set portion of the property implementation (not on both), thereby overriding the access modifier specified on the property declaration. Listing 5.37 demonstrates how to do this.

Placing Access Modifiers on the Setter

class Program
{
  static void Main()
  {
      Employee employee1 = new Employee(42);
      // ERROR: Id is read-only outside the Employee class                 
      // Employee.Id = 490;                                                
  }
}
class Employee
{
  public Employee(int id)
  {
       // Set Id property                                                  
       Id = id.ToString();                                                 
  }
  // ...
  // Id property declaration

  public string Id
  {
      get
      {
         return _Id;
      }
      // Providing an access modifier is in C# 2.0 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.

Properties as Virtual Fields

As you have seen, properties behave like virtual fields. In some instances, you do not need a backing field at all. Instead, the property getter returns a calculated value while the setter parses the value and persists it to some other member fields, if at all. Consider, for example, the Name property implementation shown in Listing 5.38. Output 5.6 shows the results.

Defining Properties

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

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

class Employee
{
  // ...
 
  public Employee(string name)
  {
      Name = name;
  }
 
  public string FirstName
  {
      get                                                                  
      {                                                                    
          return_FirstName;                                                
      }                                                                    
      set                                                                  
      {                                                                    
          // Validate FirstName assignment                                 
          if(value== null)                                                 
      {                                                                     
               // Report error                                             
               throw new NullReferenceException();                         
           }                                                               
           else                                                            
           {                                                               
               // Remove any white space around                            
               // the new last name.                                       
               value = value.Trim();                                       
               if(value== "")                                              
               {                                                           
                   throw new ApplicationException(                         
                       "FirstName cannot be blank.");                      
               }                                                           
               else                                                        
                     _FirstName = value;                                   
           }                                                           
      }                                                               
    }
    private string _FirstName;
    public string LastName
    {
        get                                                              
        {                                                                
             return_LastName;                                            
        }                                                                
        set                                                              
        {                                                                
            // Validate LastName assignment                              
            if(value== null)                                             
            {                                                            
                 // Report error                                         
                 throw new NullReferenceException();                     
            }                                                            
            else                                                         

            {                                                              
                // Remove any white space around                           
                // the new last name.                                      
                value = value.Trim();                                      
                if(value== "")                                             
                {                                                          
                    throw new ApplicationException(                        
                        "FirstName cannot be blank.");                      
                }                                                          
                else                                                       
                      _FirstName = 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 ApplicationException(                             
                    string.Format(                                           
                     "Assigned value '{0}' is invalid", value));             
              }                                                              
        }                                                                    
     }                                                                       

     // ...
  }

Output 5.6.

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.

Properties and Method Calls Not Allowed as ref or out Parameter Values

C# allows properties to be used identically to fields, except when they are passed as ref or out parameter values. ref and out parameter values are internally implemented by passing the memory address to the target method. However, because properties can be virtual fields that have no backing field, or can be read/write-only, it is not possible to pass the address for the underlying storage. As a result, you cannot pass properties as ref or out parameter values. The same is true for method calls. Instead, when code needs to pass a property or method call as a ref or out parameter value, the code must first copy the value into a variable and then pass the variable. Once the method call has completed, the code must assign the variable back into the property.