It always seems to just "work" without ever having to do anything.
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 Equals
and GetHashCode
are okay (Equals
checks if the fields are equals, and GetHashCode
is based on the fields (not necessarily all of them!)). If you're using reference types, the default implementation of Equals
and GetHashCode
use reference equality, which may or may not be okay; it depends on what you're doing.
The only thing I can think of is that each class has a hidden sort of static identifier that Object.GetHashCode
uses.
No. The default is a hash code based on the fields for a value type, and the reference for a reference type.
(also, does anyone know how Object.GetHashCode is implemented? I couldn't find it in the .NET Reflector)
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.
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?
Well, is default equality okay for you? If not, override Equals
and GetHashCode
or implmenet IEqualityComparer<T>
for your T
.
I'd still like to know how the magic works, though =P
Every object has Equals
and GetHashCode
. The default implementations are as follows:
- For value types,
Equals
is value equality.
- For reference types,
Equals
is reference equality.
- For value types,
GetHashCode
is based on the fields (again, not necessarily all of them!).
- For reference types,
GetHashCode
is based on the reference.
If you use a overload of Dictionary
constructor that doesn't take a IEqualityComparer<T>
for your T
, it will use EqualityComparer<T>.Default
. This IEqualityComparer<T>
just uses Equals
and GetHashCode
. So, if you haven't overridden them, you get the implementations as defined above. If you override Equals
and GetHashCode
then this is what EqualityComparer<T>.Default
will use.
Otherwise, pass a custom implementation of IEqualityComparer<T>
to the constructor for Dictionary
.