C Sharp

Advanced Use of Properties

So far, I've talked about properties being useful for the following reasons: -

  • They provide a level of abstraction to clients.

  • They provide a generic means of accessing class members by using the object.field syntax.

  • They enable a class to guarantee that any additional processing can be done when a particular field is modified or accessed.

The third item points us to another helpful use for properties: the implementation of something called lazy initialization. This is an optimization technique whereby some of a class's members are not initialized until they are needed.

Lazy initialization is beneficial when you have a class that contains seldom-referenced members whose initialization takes up a lot of time or chews up a lot of resources. Examples of this would be situations where the data has to be read from a database or across a congested network. Because you know these members are not referenced often and their initialization is expensive, you can delay their initialization until their getter methods are called.

To illustrate this, let's say you have an inventory application that sales representatives run on their laptop computers to place customer orders and that they occasionally use to check inventory levels. Using properties, you could allow the relevant class to be instantiated without the inventory records having to be read, as shown in the code below. Then, if a sales rep did want to access the inventory count for the item, the getter method would access the remote database at that time.

    class Sku
    {
        protected double onHand;
        public string OnHand
        {
            get
            {
                // Read from central db and set onHand value.
                return onHand;
            }
        }
    }

As you've seen throughout this chapter so far, properties enable you to provide accessor methods to fields and a generic and intuitive interface for the client. Because of this, properties are sometimes referred to as smart fields. Now, let's take this a step further and look at how arrays are defined and used in C#. We'll also see how properties are used with arrays in the form of indexers.