I have used Dictionary(TKey, TValue) for many purposes. But I haven't encountered any scenario to implement GetHashCode() which I believe is because my keys were of primary types like int and string.
I am curious to know the scenarios (real world examples) when one should use a custom object for key and thus implement methods GetHashCode() Equals() etc.
And, does using a custom object for key necessitate implementing these functions?
Best Answer
You should override
Equals
andGetHashCode
whenever the defaultObject.Equals
(tests for reference equality) will not suffice. This happens, for example, when the type of your key is a custom type and you want two keys to be considered equal even in cases when they are not the same instance of the custom type.For example, if your key is as simple as
and you want two
Point
s two be considered equal if theirX
s are equal and theirY
s are equal then you will need to overrideEquals
andGetHashCode
.