#249 – Using a get Accessor to Clean up Property Data

It’s not always the case that when you read a property’s value, you want exactly the same value that you wrote to the property.

As an example, imagine that we have a Dog.ShowDogName property that lets us read/write our dog’s official “show dog” name.  Show dog names are titles, so each word should be capitalized.  For convenience, we’d like the client code to not worry about the capitalization, but have the class take care of it.

We store the property in its original non-capitalized state and then clean up the name by capitalizing it whenever the property is read.

        private string showDogName;
        public string ShowDogName
                return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(showDogName);

                showDogName = value;

Here’s an example of some client code using the new property:

            kirby.ShowDogName = "fitzgerald's rich socialite mister stinks-a-lot";

            // Fitzgerald's Rich Socialite Mister Stinks-A-Lot

#244 – Defining a Get Accessor for a Property

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

The get accessor is defined using the get keyword.  The get accessor should return a value of the same type as the property itself.  You often just return the value of an internal private variable, which is known as the backing field.

In the example below, we define a get accessor for a property and return the value of the internal backing field whenever the property is read.

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

    public string Name
        // Get accessor allows the property to be read
        get { return name; }

Below is an example of the Name property being read.

    // Read the Name property
    string objectName = myObject.Name;

#243 – Property Get and Set Accessors

You can define a property in a class as a way of encapsulating a private field.  When declaring a property in a class, you define the property’s type, its name, and code for the property’s accessors.  The accessors are the means by which a user of the class reads and writes the property’s value.

When defining the accessors, you can have one of the following combinations:

  • Just a get accessor   (property is read-only)
  • Just a set accessor  (property is write-only)
  • Both get/set accessors  (property is read/write)

The get accessor defines the code that executes when some code tries to read the property’s value.

The set accessor defines the code that executes when a property value is written to.