Consider this example, it shows two possible ways of lazy initialization. Except for being thread-safe, are there any specific advantates of using Lazy<T> here?
class Customer {
private decimal? _balance2;
private static decimal GetBalanceOverNetwork() {
//lengthy network operations
Thread.Sleep(2000);
return 99.9M;
}
public decimal? GetBalance2Lazily() {
return _balance2 ?? (_balance2 = GetBalanceOverNetwork());
}
private readonly Lazy<decimal> _balance1 = new Lazy<decimal>(GetBalanceOverNetwork);
public Lazy<decimal> Balance1 {
get { return _balance1; }
}
}
UPDATE:
Please consider above code as a simple example, data types are irrelevant, the point here is to compare Lazy <T> over standard lazy initialization.
_balance1
is alreadyreadonly
, and the accessor doesn't do anything besides return the value, what are you gaining from using a property? – Bronkprivate set
and constructor, no? – GainLazy<T>
does not have an implicit (or explicit) conversion toT
. – ThelenLazy<T>
in your public property? I would have return its value. And why is your first public propertyDecimal?
? That the private fields are of these types is understandable. But leaking details about your lazy initialization into the public API is probably not a wise choice. – Oxalis