#245 – Defining a Set Accessor for a Property

A set accessor for a property is the code that executes when the client of an object tries to write the property’s value.

The set accessor is defined using the set keyword.  The new property value is accessible using the value keyword, which is treated as a local variable having the same type as the property.

It’s common to store the value of a property in an internal private variable, known as the backing field.

In the example below, the set accessor for a property stores the new property value in the internal backing field whenever the property is written.  Note that the private variable and the public property name differ only in their case (name vs. Name).

    // Backing field--where the property value is actually stored
    private string name;

    public string Name
    {
        // Set accessor allows the property to be written
        set
        {
            name = value;
        }
    }
Advertisements