There are two issues that you should consider - both of which suggest that this is a bad idea.
First, inheriting from .NET BCL collection types is usually not a good idea. The main reason for this is that most of the methods of these types (for example, Add and Remove ) are not virtual - and if you provide your own implementations in a derived class, they will not be called if you pass your collection as a base type. In your case, hiding the indexer Dictionary<TK,TV> property, you create a situation where a call using a base class reference will do something other than a call using a derived class reference ... violation Liskov replacement principle :
var derived = new D(); var firstItem = derived["puppy"];
Secondly, and more importantly , creating an indexer that inserts an element when you try to find one is completely unexpected . Indexers clearly defined get and set operations - implementing a get operation to modify a collection is very bad.
In this case, you will greatly improve the creation of an extension method that can work with any dictionary. Such an operation is no less surprising in what it does, and also does not require the creation of a derived type of collection:
public static class DictionaryExtensions { public static TValue FindOrAdd<TKey,TValue>( this IDictionary<TKey,TValue> 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; } }
Lbushkin
source share