#610 – Lazy Evaluation in Property Get Accessors
June 21, 2012 1 Comment
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.
I prefer to write such code as one-liner:
private string fullDogDescription = null;
public string FullDogDescription
{
get { return fullDogDescription ?? ( fullDogDescription = GenerateDogDescription() ); }
}