title: Caching return value of an extension method
body: <p>Here is pseudo code of what this would look like if I could modify the class in question</p>
  
  <pre><code>public class Foo
  {
      private TheDataType _Data;
      public TheDataType GetData()
      {
          if (_Data != null)
              return _Data;
  
          // fetch/generate data
  
          return _Data;
      }
  }
  </code></pre>
  
  <p>How do I turn this into an extension method? The definition/scope of the <code>_Data</code> is what bothers me...</p>
  
  <p>================================================</p>
  
  <p>This is probably the closest to what I want, but feel like an overkill for something so simple</p>
  
  <pre><code>public static class FooExtensions
  {
      private static ConcurrentDictionary&lt;Foo,TheDataType&gt; DataCache = new ConcurrentDictionary&lt;Foo,TheDataType&gt;();
      public static TheDataType GetData(this Foo foo)
      {
          TheDataType data;
          if (DataCache.TryGetValue(foo, out data))
              return data
  
          // fetch/generate data
  
          DataCache.Add(foo, data);
          return data;
      }
  }
  </code></pre>