C Sharp

Defining and Using Properties

Using accessor methods works well and is a technique used by programmers of several object-oriented languages, including C++ and Java. However, C# provides an even richer mechanism-properties-that has the same capabilities as accessor methods and is much more elegant on the client side. Through properties, a programmer can write a client that can access a class's fields as though they are public fields without knowing whether an accessor method exists.

A C# property consists of a field declaration and accessor methods used to modify the field's value. These accessor methods are called getter and setter methods. Getter methods are used to retrieve the field's value, and setter methods are used to modify the field's value. Here's the earlier example rewritten using C# properties: -

    class Address
    {
        protected string city;
        protected string zipCode;
        public string ZipCode
        {
            get
            {
                return zipCode;
            }
            set
            {
                // Validate value against some datastore.
                zipCode = value;
                // Update city based on validated zipCode.
            }
        }
    }

Notice that I created a field called Address.zipCode and a property called Address.ZipCode. This can confuse some people at first because they think Address.ZipCode is the field and wonder why it needs to be defined twice. But it's not the field. It's the property, which is simply a generic means of defining accessors to a class member so that the more intuitive object.field syntax can be used. If in this example I were to omit the Address.zipCode field and change the statement in the setter from zipCode = value to ZipCode = value, I'd cause the setter method to be called infinitely. Also notice that the setter doesn't take any arguments. The value being passed is automatically placed in a variable named value that is accessible inside the setter method.(You'll soon see in MSIL how this bit of magic happens.) -

Now that we've written the Address.ZipCode property, let's look at the changes needed for the client code: -

    Address addr = new Address();
    addr.ZipCode = "55555";
    string zip = addr.ZipCode;

As you can see, how a client accesses the fields is intuitive: no more guessing or looking through documentation (aka the source code) to determine whether a field is public and, if not, what the name of the accessor method is.

by BrainBellupdated
Advertisement: