views:

276

answers:

7

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?

+10  A: 

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.

Marc Gravell
A: 

This is called Lazy initialization

Matt Breckon
+1  A: 

Lazy Initialization.

GraemeF
+12  A: 

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; }
}
LukeH
Nice, I knew this could be encapsulated somehow
Trent
You get the answer for extra effort.
Trent
+1 bazillion for mentioning the Lazy class. I was unaware of it, and now have another thing to look forward to.
Randolpho
A: 

lazy initializer

Benny
A: 

Lazy load

Mark
+1  A: 

I cant post comments yet. :(

It should be noted that you need to be aware of side effects in the OP code. That code could return inconsistent results for concurrent requests to the property.

Not sure if that happens with LazyLoad as well.

Its not bad, just worth noting if you use lazy initializers regularly.

GrayWizardx