title: Overloading the index operators in a Dictionary subclass
body: <p>I have a situation where I for quite a while I've be reconstructing a set of data into a .NET Dictionary when a service comes up.  Lately that set of Data has gotten so large, I decided I just want to actually build the kev/value objects on demand.  So my though is, inherit from Dictionary, and overload the index operators.  There I'll check to see if the collection contains the key (and return the value), and if it doesn't, I'll create the object populate it to the collection and return it.</p>
  
  <p>I try the following code (for simplicity I've just made the value of type string instead of the rather complex object I actually create):</p>
  
  <pre><code>  public class BroadcastDictionary&lt;TKey, TItem&gt; : Dictionary&lt;TKey, TItem&gt;
    {
       public string this[TKey key]
       {
          get
          {
             if (!base.ContainsKey(key))
             {
                try
                {
                   //Construct the object and put it
                   // into the collection:
                   string newValue = "new value!";
                   base.Add((TKey)key, (TItem)newValue);
                }
                catch
                {
                   ;// Log the lazy object generation failure
                }
             }
  
             if (base.ContainsKey(key))
                return base[key].ToString();
             else
                throw new Exception("BroadcastDictionary value object lazy load failure.");
          }
       }
    }
  </code></pre>
  
  <p>However, I get hung up on not being able insert the value using <code>Dictionary.Add(key, value)</code>.  Any thoughts on how I might repair and make functional this piece of code?</p>
  
  <p>EDIT: The problem is that the above code does not compile.  At the <code>base.Add((TKey) key, (TItem)newValue);</code> the compiler reports error "Error   2   Cannot convert type 'string' to 'TItem'".</p>