C# – Why is there no generic implementation of OrderedDictionary in .net

cnet

Why did Microsoft not provide generic implementation of OrderedDictionary?

There are a few custom implementations I've seen, including: http://www.codeproject.com/KB/recipes/GenericOrderedDictionary.aspx

But why did Microsoft not include it in the base .net library? Surely they had a reason for not building a generic…. but what is it?

Prior to posting this message, I did see:
https://stackoverflow.com/questions/2629027/no-generic-implementation-of-ordereddictionary

But that just confirms that it does not exist. Not why it does not exist.

Thanks

Best Answer

The OrderedDictionary overloads the indexing operation so that indexing with an integer N will get the item in position N, while indexing with an Object will retrieve the item coresponding to that object. If one were to create an OrderedDictionary<int, string> called myDict, and added items (1,"George") and (0,"Fred") in that order, should myDict[0] return "George" or "Fred"?

Such an issue could have been resolved by imposing a class constraint on the key type. On the other hand, much of the usefulness of generic collections stems from their ability to efficiently work with value types. Imposing a class constraint on the key type would seem a little ugly.

If the class didn't have to be CLS compliant but merely had to work with vb.net, a sensible design might have been to used named indexed properties. Thus, in the example above, myDict.ByKey[0] would have yielded "Fred", and myDict.BySequence[0] would have yielded "George". Unfortunately, languages like C# do not support named indexed properties. While one could have kludged something to allow use of the above syntax even without such properties, the unfortunate decision to wrap the fields of structures like Point and Rectangle means that for myDict.ByKey[0] = "Wally" to work, myDict.ByKey would have to return a new class object. A struct would be more efficient, but compilers would reject what looked like a write to a read-only structure (notwithstanding that the property wouldn't modify the struct returned by ByKey, but instead modify the collection to which it holds a reference).

Personally, I think a dictionary-ish object that was specified as keeping track of the insertion order would be a nice thing to have; I'd also like to have a dictionary-ish object which could easily return the key associated with a particular key (so that, e.g. if one has a case-insensitive dictionary and has added a record with a key of "GEORGE", one could ask the dictionary what key is associated with "George" without having to search through all the KeyValuePair objects returned in an enumeration.