title: C#: How to implement a smart cache
body: <p>I have some places where implementing some sort of cache might be useful. For example in cases of doing resource lookups based on custom strings, finding names of properties using reflection, or to have only one <code>PropertyChangedEventArgs</code> per property name.</p>
  
  <p>A simple example of the last one:</p>
  
  <pre><code>public static class Cache
  {
      private static Dictionary&lt;string, PropertyChangedEventArgs&gt; cache;
      static Cache()
      {
          cache = new Dictionary&lt;string, PropertyChangedEventArgs&gt;();
      }
      public static PropertyChangedEventArgs GetPropertyChangedEventArgs(
          string propertyName)
      {
          if (cache.ContainsKey(propertyName))
              return cache[propertyName];
  
          return cache[propertyName] = new PropertyChangedEventArgs(propertyName);
      }
  }
  </code></pre>
  
  <p>But, will this work well? For example if we had a whole load of different propertyNames, that would mean we would end up with a huge cache sitting there never being garbage collected or anything. I'm imagining if what is cached are larger values and if the application is a long-running one, this might end up as kind of a problem... or what do you think? How should a good cache be implemented? Is this one good enough for most purposes? Any examples of some nice cache implementations that are not too hard to understand or way too complex to implement?</p>