When is it acceptable for an indexer to automatically add items to a collection/dictionary? Is this reasonable, or contrary to best practices?
public class I { /* snip */ }
public class D : Dictionary<string, I>
{
public I this[string name]
{
get
{
I item;
if (!this.TryGetValue(name, out item))
{
item = new I();
this.Add(name, item);
}
return item;
}
}
}
Sample of how this may be used in a collection:
public class I
{
public I(string name) {/* snip */}
public string Name { get; private set; }
/* snip */
}
public class C : Collection<I>
{
private Dictionary<string, I> nameIndex = new Dictionary<string, I>();
public I this[string name]
{
get
{
I item;
if (!nameIndex.TryGetValue(name, out item))
{
item = new I(name);
this.Add(item); // Will also add the item to nameIndex
}
return item;
}
}
//// Snip: code that manages nameIndex
// protected override void ClearItems()
// protected override void InsertItem(int index, I item)
// protected override void RemoveItem(int index)
// protected override void SetItem(int index, I item)
}
There’s two problems that you should consider – both of which suggest this is a bad idea.
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
AddandRemove) 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 theDictionary<TK,TV>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 Liskov Substitution Principle:Second, and more importantly, creating an indexer that inserts an item when you attempt to find one is entirely unexpected. Indexers have clearly defined
getandsetoperations – implementing thegetoperation to modify the collection is very bad.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: