[Previous] [Contents] [Next]

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.
            }
        }
    }

[Previous] [Contents] [Next]