Reputation: 27295
I find myself writing a lot of code like this:
private Foo _CacheFoo;
public Foo GetFoo() {
if (this._CacheFoo == null) {
this._CacheFoo = new Foo();
}
return this.CacheFoo;
}
private Bar _CacheBar;
public Bar GetBar() {
if (this._CacheBar == null) {
this._CacheBar = new Bar();
}
return this._CacheBar;
}
I'm wondering if there is a sensible way to encapsulate the caching part of that.
Upvotes: 0
Views: 32
Reputation: 26856
Well, you can use some syntactic sugar, it slightly reduces amount of code:
private Foo _CacheFoo;
public Foo GetFoo()
{
return _CacheFoo ?? (_CacheFoo = new Foo());
}
Upvotes: 1
Reputation: 151594
You could use Lazy<T>
:
private Lazy<Foo> _foo = new Lazy<Foo>(() => new Foo());
public Foo GetFoo()
{
return _foo.Value;
}
Though that still is relatively a lot to type per instance you want to return.
Upvotes: 2