Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>There's two problems that you should consider - both of which suggest this is a bad idea.</strong></p> <p>First, inheriting from the .NET BCL collection types is not generally a good idea. The main reason for this is that most methods on those types (like <code>Add</code> and <code>Remove</code>) are not virtual - and if you provide your own implementations in a derived class, they will not get called if you pass your collection around as the base type. In your case, by hiding the <code>Dictionary&lt;TK,TV&gt;</code> indexer property, you are creating a situation where a call using a base-class reference will do something different than a call using a derived-class reference ... a violation of the <a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle" rel="noreferrer">Liskov Substitution Principle</a>:</p> <pre><code>var derived = new D(); var firstItem = derived["puppy"]; // adds the puppy entry var base = (Dictionary&lt;string,I&gt;)derived; var secondItem = base["kitten"]; // kitten WAS NOT added .. BAD! </code></pre> <p><strong>Second, and more importantly</strong>, creating an indexer that inserts an item when you attempt to find one <strong>is entirely unexpected</strong>. Indexers have clearly defined <code>get</code> and <code>set</code> operations - implementing the <code>get</code> operation to modify the collection is very bad.</p> <p>For the case you describe, you're much better off creating an extension method that can operate on any dictionary. Such an operation is both less surprising in what it does, and also doesn't require creating a derived collection type:</p> <pre><code>public static class DictionaryExtensions { public static TValue FindOrAdd&lt;TKey,TValue&gt;( this IDictionary&lt;TKey,TValue&gt; dictionary, TKey key, TValue value ) where TValue : new() { TValue value; if (!this.TryGetValue(key, out value)) { value = new TValue(); this.Add(key, value); } return value; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload