In the following code:
public class SomeClass
{
// ... constructor and other stuff
public in SomeProperty
{
get
{
return SomeHeavyCalculation();
}
}
}
I consider the class to be immutable, so every time SomeProperty is accessed, same value should be returned. My question is whether it is possible to avoid calculating the value each time. Is there some built in mechanism for caching such stuff?
Yup –
Lazy<T>, assuming you’re using .NET 4:I assume you’re trying to avoid performing the calculation if the property is never accessed. Otherwise, just perform it upfront on construction.
Note that properties are often understood to be “cheap” to evaluate – and while you’re making this lazy so that later accesses are cheap, this is still potentially going to be “heavy” enough on the first access to make a property inappropriate. Consider a
ComputeXyzmethod instead.