Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this C# pattern for property initialization?

I'll often have objects with properties that use the following pattern:

private decimal? _blah;
private decimal Blah
{
    get
    {
        if (_blah == null)
            _blah = InitBlah();
        return _blah.Value;
    }
}

Is there a name for this method?

like image 758
Trent Avatar asked Dec 10 '09 16:12

Trent


2 Answers

Lazy initialisation.

.NET 4, when it arrives, will have a Lazy<T> class built-in.

private readonly Lazy<decimal> _blah = new Lazy<decimal>(() => InitBlah());
public decimal Blah
{
    get { return _blah.Value; }
}
like image 80
LukeH Avatar answered Sep 21 '22 13:09

LukeH


Lazy loading, deferred initialization, etc.

Noet that InitBlah should (in this case) ideally return decimal, not decimal? to avoid the chance that it gets called lots of times because it is legitimately null.

like image 32
Marc Gravell Avatar answered Sep 19 '22 13:09

Marc Gravell