12 March 2007

Reference type keys and .NET dictionaries

The default implementation of the Equals method for reference types is to call ReferenceEquals i.e. to test whether two variables reference the same instance of an object.

When using a ListDictionary the Equals method is used so you can be sure you will be accessing the correct item. However if you use a HybridDictionary, which will swap to a Hashtable for collections of more than 10 items, you can get inconsistent results. This is all down to the fact that the Hashtable uses the GetHashCode method to get a code which represents an object and this is then used as the key. As you will read here the GetHashCode method does not always return a unique code for dissimilar objects so you can end up accessing the wrong item of your dictionary.

To get around this you can either stick to using the ListDictionary or implement your own IHashCodeProvider for the classes used as keys in your dictionary.

No comments: