tags:

views:

247

answers:

1

The System.Collections.Specialized.NameObjectCollectionBase class is used extensively at my company as the basis of collection classes. (Let's not get into questioning why.) I recently came across a situation where I needed to add an object at a specific index, but the functionality wasn't there. At first I wondered why we had left that functionality out of our collection classes, but I soon discovered that the functionality is missing from NameObjectCollectionBase!

You can access objects in the collection by index (BaseGet(int index)).
You can remove objects from the collection by index (BaseRemoveAt(int index)).
But you can't insert an object at a specific index.

I can't think of a good reason why this functionality isn't available. Can you?

[Update]The underlying implementation is not just a hashtable. The collection maintains both a Hashtable and an ArrayList. You can verify this using Reflector.

A: 

Because the underlying implementation is a hashtable and inserting directly into it would break it (index is related to the hash of the key). Expecting what is a hash, except in name, to be ordered (i.e., a particular element exists between two others) in an a sequence not related to the hash of the key value seems a little odd. If you need it to be ordered, you're probably better off using an OrderedDictionary or SortedDictionary<T,T>.

More info on NameObjectCollectionBase, OrderedDictionary, and SortedDictionary<T,T>.

tvanfosson