It always seems to just “work” without ever having to do anything.
The only thing I can think of is that each class has a hidden sort of static identifier that Object.GetHashCode uses. (also, does anyone know how Object.GetHashCode is implemented? I couldn’t find it in the .NET Reflector)
I have never overridden GetHashCode but I was reading around and people say you only need to when overriding Equals and providing custom equality checking to your application so I guess I’m fine?
I’d still like to know how the magic works, though =P
You didn’t tell us if you’re using value types or reference types for your keys.
If you’re using value types, the default implementation of
EqualsandGetHashCodeare okay (Equalschecks if the fields are equals, andGetHashCodeis based on the fields (not necessarily all of them!)). If you’re using reference types, the default implementation ofEqualsandGetHashCodeuse reference equality, which may or may not be okay; it depends on what you’re doing.No. The default is a hash code based on the fields for a value type, and the reference for a reference type.
It’s an implementation detail that you should never ever need to know, and never ever rely on it. It could change on you at any moment.
Well, is default equality okay for you? If not, override
EqualsandGetHashCodeor implmenetIEqualityComparer<T>for yourT.Every object has
EqualsandGetHashCode. The default implementations are as follows:Equalsis value equality.Equalsis reference equality.GetHashCodeis based on the fields (again, not necessarily all of them!).GetHashCodeis based on the reference.If you use a overload of
Dictionaryconstructor that doesn’t take aIEqualityComparer<T>for yourT, it will useEqualityComparer<T>.Default. ThisIEqualityComparer<T>just usesEqualsandGetHashCode. So, if you haven’t overridden them, you get the implementations as defined above. If you overrideEqualsandGetHashCodethen this is whatEqualityComparer<T>.Defaultwill use.Otherwise, pass a custom implementation of
IEqualityComparer<T>to the constructor forDictionary.