If I place a key object in an Dictionary that doesn’t implement Equals and GetHashCode how does the Dictionary ContainsKey work? By checking the references are equal?
Thanks
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The base
Objectclass implements Equals and GetHashCode. All classes inherit fromObjectby default. The dictionary will just use these implementations.The default implementation of Equals tests object references, which will probably be fine in most cases for your dictionary.
The base implementation of GetHashCode is fairly naive, in fact even the documentation states:
So the recommendation is to override it yourself if you intend to use an object as a dictionary or hashtable key.
With regards to how this works. Remember that GetHashCode isn’t actually critical for the implementation of a dictionary. hash codes are allowed to clash, that is kind of the point. The hash code is just used to help with locating an object, is it the equality test that will be used to check the object is the correct one in the end. Lets just say for arguments sake that every object just returned a hash code of 1. They would all end up in the same pot in the dictionary, probably in some fairly random order (perhaps inserted order) and it would just fall back to using
Equalsto verify the object identity. It wouldn’t be efficient, but it would work fine.So, if you are looking for efficiency, you should consider overriding GetHashCode, but if it’s just going to be a small dictionary and efficiency isn’t too important, you’ll be fine just to leave it with the default.
[All the usual considerations apply. It’s best not override GetHashCode for mutable objects, and make 100% sure that objects that return true for Equals() return the same hash code.]