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:
public class SomeClass
{
private readonly Lazy<Foo> foo = new Lazy<Foo>(SomeHeayCalculation);
// ... constructor and other stuff
public Foo SomeProperty
{
get
{
return foo.Value;
}
}
}
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 ComputeXyz
method instead.
Just cache the calculation in a private variable
like so:
public class SomeClass
{
// ... constructor and other stuff
private int? calculation = null;
public int SomeProperty
{
get
{
if (!calculation.HasValue)
calculation = SomeHeayCalculation();
return calculation.Value;
}
}
}
Other than what Jon suggested, you could use this pattern:
public class SomeClass
{
// ... constructor and other stuff
private Foo _foo;
public Foo SomeProperty
{
get
{
return _foo ?? (_foo = SomeHeayCalculation());
}
}
}
It's worth noting that this really breaks down (read: becomes less readable) for value types, unless you want to wrap them in Nullable<T>
. In that's your case, you may want to stick with Lazy<T>
if available.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With