Question

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.

Was it helpful?

Solution

It is semantically more correct.

When you use the Nullable<decimal>, what you say is that the value of null will stand for the "unevaluated" state. Although this is a common conversion, it is still arbitrary. There are million other ways to interpret null, so you should probably explain somewhere (in the documentation or at least as a comment) what null means in this case.

On the contrary, when you use Lazy<decimal>, your intentions are clear.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top