Feature request 3: Lazy Initialization

It would be great to be able to convert an instance variable initialization
into a lazy load property (general concept described by Fowler at
http://www.martinfowler.com/eaaCatalog/lazyLoad.html); something like this:

Before:
private FooBar _fooBar = new FooBar();

After:
private FooBar _fooBar = null;
...
private FooBar LazyFooBar // coming up with an apropriate name here is
always a challenge...
{
get
{
if (_fooBar == null)
_fooBar = new FooBar();
return _fooBar;
}
}
(plus all usages of _fooBar would be replaced with LazyFooBar).

Thanks,
Oskar Austegard



2 comments
Comment actions Permalink

Hello,

Just a warning: the Before code is thread-safe, but the After code is
not (more than one FooBar could be created and returned at the same time).

Oskar Austegard wrote:

It would be great to be able to convert an instance variable initialization
into a lazy load property (general concept described by Fowler at
http://www.martinfowler.com/eaaCatalog/lazyLoad.html); something like this:

Before:
private FooBar _fooBar = new FooBar();

After:
private FooBar _fooBar = null;
...
private FooBar LazyFooBar // coming up with an apropriate name here is
always a challenge...
{
get
{
if (_fooBar == null)
_fooBar = new FooBar();
return _fooBar;
}
}

0
Comment actions Permalink

See:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpatterns/html/ImpSingletonInCsharp.asp

"Joe Cheng" <code@joecheng.com> wrote in message
news:ch54m6$efq$1@is.intellij.net...

Hello,

>

Just a warning: the Before code is thread-safe, but the After code is not
(more than one FooBar could be created and returned at the same time).

>

Oskar Austegard wrote:

>> It would be great to be able to convert an instance variable
>> initialization
>> into a lazy load property (general concept described by Fowler at
>> http://www.martinfowler.com/eaaCatalog/lazyLoad.html); something like
>> this:
>>
>> Before:
>> private FooBar _fooBar = new FooBar();
>>
>> After:
>> private FooBar _fooBar = null;
>> ...
>> private FooBar LazyFooBar // coming up with an apropriate name here is
>> always a challenge...
>> {
>> get
>> {
>> if (_fooBar == null)
>> _fooBar = new FooBar();
>> return _fooBar;
>> }
>> }


0

Please sign in to leave a comment.