title: Which mechanism is a better way to extend Dictionary to deal with missing keys and why?
body: <p>There is a minor annoyance I find myself with a lot - I have a <code>Dictionary&lt;TKey, TValue&gt;</code> that contains values that may or may not be there.</p>
  
  <p>So normal behaviour would be to use the indexer, like this:</p>
  
  <pre><code>object result = myDictionary["key"];  
  </code></pre>
  
  <p>However, if <code>"key"</code> is not in the dictionary this throws a <code>KeyNotFoundException</code>, so you do this instead:</p>
  
  <pre><code>object val;
  if (!myDictionary.TryGetValue("key", out val))
  {
      val = ifNotFound;
  }
  </code></pre>
  
  <p>Which is fine, except that I can have a load of these in a row - <code>TryGetValue</code> starts to feel awful clunky.</p>
  
  <p>So option 1 is an extension method:</p>
  
  <pre><code>public static TValue TryGet&lt;TKey, TValue&gt;(
      this Dictionary&lt;TKey, TValue&gt; input, 
      TKey key, 
      TValue ifNotFound = default(TValue))
  {
      TValue val;
      if (input.TryGetValue(key, out val))
      {
          return val;
      }
  
      return ifNotFound;
  }
  </code></pre>
  
  <p>Which lets me do:</p>
  
  <pre><code>object result = myDictionary.TryGet("key1") ?? ifNotFound;
  
  int i = anotherDictionary.TryGet("key2", -1);
  </code></pre>
  
  <p>Which is simple enough, but an additional extension method with a name similar to existing instance methods potentially adds confusion and reduces maintainability. It's also not consistent with the dictionary's indexer set - that will handle missing keys.</p>
  
  <p>So option 2 is a new implementation of <code>IDictionary&lt;TKey, TValue&gt;</code> with a implicit cast from <code>Dictionary&lt;TKey, TValue&gt;</code> but an indexer that returns <code>default(TValue)</code> instead of throwing a <code>KeyNotFoundException</code>.</p>
  
  <p>That let's me do:</p>
  
  <pre><code>ForgivingDictionary&lt;string, object&gt; dict = myDictionary;
  
  object val = dict["key"] ?? ifNotFound;
  
  // do stuff to val, then...
  dict["key"] = val;
  </code></pre>
  
  <p>So now the get and set values are consistent, but value types are messier and <code>ForgivingDictionary</code> involves a lot more code.</p>
  
  <p>Both methods seem 'messy' - is there a better way to do this already in .Net?</p>
  
  <p>Both methods make compromises that could cause confusion, but is one more obvious/clear than the other? And why? </p>