William Jockusch
William Jockusch

Reputation: 27295

Create-or-return-cached object

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

Answers (2)

Andrey Korneyev
Andrey Korneyev

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

CodeCaster
CodeCaster

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

Related Questions