#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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: