C Sharp

Properties as Smart Fields

As an example, let's say that you have an address class with a ZIP code field and a city field. When the client modifies the Address.ZipCode field, you want to validate the ZIP code against a database and automatically set the Address.City field based on that ZIP code. If the client had direct access to a public Address.ZipCode member, you'd have no easy way of doing either of these things because changing a member variable directly doesn't require a method. Therefore, instead of granting direct access to the Address.ZipCode field, a better design would be to define the Address.ZipCode and Address.City fields as protected and provide an accessor methods for getting and setting the Address.ZipCode field. This way, you can attach code to the change that performs any additional work that needs to be done.

This ZIP code example would be programmed in C# as follows. Notice that the actual ZipCode field is defined as protected and, therefore, not accessible from the client and that the accessor methods, GetZipCode and SetZipCode, are defined as public.

    class Address
    {
        protected string ZipCode;
        protected string City;
        public string GetZipCode()
        {
            return this.ZipCode;
        }
        public void SetZipCode(string ZipCode)
        {
            // Validate ZipCode against some datastore.
            this.ZipCode = ZipCode;
            // Update this.City based on validated ZIP code.
        }
    }

The client would then access the Address.ZipCode value like this: -

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