#610 – Lazy Evaluation in Property Get Accessors

One of the benefits in using a property in a class, rather than a public field, is that you can delay calculation of the property’s value until client code actually tries to read the value.

In the code below, we define a FullDogDescription property that is read-only.  The private backing variable is initialized to an empty string and we only calculate its value in the get accessor when someone tries to read the property’s value.

<pre>        private string fullDogDescription = "";
        public string FullDogDescription
        {
            get
            {
                // Generate full description the first time that
                // someone reads this property.
                if (fullDogDescription == "")
                    fullDogDescription = GenerateDogDescription();

                return fullDogDescription;
            }
        }

The benefit of doing this is that if the call to GenerateDogDescription takes some time, we don’t spend the time calculating a value until some piece of code actually needs a value.

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #610 – Lazy Evaluation in Property Get Accessors

  1. Mikhail says:

    I prefer to write such code as one-liner:

    private string fullDogDescription = null;

    public string FullDogDescription
    {
    get { return fullDogDescription ?? ( fullDogDescription = GenerateDogDescription() ); }
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: