I need to use a class that I have written as the type of the key for a Dictionary
I read the documentation on MSDN about the default constructor of Dictionary
Dictionary<TKey, TValue>requires an equality implementation to
determine whether keys are equal. This constructor uses the default
generic equality comparer,EqualityComparer<T>.Default. If type
TKeyimplements theSystem.IEquatable<T>generic interface, the
default equality comparer uses that implementation. Alternatively, you
can specify an implementation of theIEqualityComparer<T>generic
interface by using a constructor that accepts a comparer parameter.
This makes think that the only thing I have to do is to have my class for the key implement System.IEquatable<T>
However i’m very surprised that System.IEquatable<T> doesn’t have a HashCode() method.
So will the Dictionary created this way use a hash code? If yes where does it come from ? Otherwise, will my Dictionary have constant cost access operations (I don’t think it’s achievable without a hash code)
It still uses the overridden
object.GetHashCode()method to obtain the hash code. The reason that there is a separateIEquatable<T>interface (i.e. why the defaultEqualityComparer<T>doesn’t always just call the overriddenobject.Equals()method to compare two objects) is for performance reasons –object.Equals()takes anobjectargument and therefore the implementation has to cast it to the target type before it can perform a meaningful comparison (value types also have to be boxed and unboxed); whereas the argument toIEquatable<T>.Equals()is already of typeT. This performance consideration doesn’t apply to theGetHashCode()method since it takes no argument, hence there is no reason for it to exist on theIEquatable<T>interface.