C Sharp

Read-Only Properties

In the example we've been using, the Address.ZipCode property is considered read/write because both a getter and a setter method are defined. Of course, sometimes you won't want the client to be able to set the value of a given field, in which case you'll make the field read-only. You do this by omitting the setter method. To illustrate a read-only property, let's prevent the client from setting the Address.city field, leaving the Address.ZipCode property as the only code path tasked with changing this field's value: -

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

Inheriting Properties

Like methods, a property can be decorated with the virtual, override, or abstract modifiers I covered in Chapter 6, "Methods." This enables a derived class to inherit and override properties just as it could any other member from the base class. The key issue here is that you can specify these modifiers only at the property level. In other words, in cases where you have both a getter method and a setter method, if you override one, you must override both.