Should I implement non-generic GetHashCode
and Equals
if my class implements IEqualityComparer<T>
?
Update:
My hope was that MS updated implementation of their collection when they introduced IEqualityComparer<T>
. So I thought that Dictionary
and any other collection classes will check internally if my class implements IEqualityComparer<T>
and use not generic methods GetHashCode
and Equals
only if that interface is not implemented. Without collections support that interface has very little value.
Update2:
I just checked Dictionary.FindEntry(TKey key)
using ILSpy. It uses IEqualityComparer<TKey>
(varriable comparer
below). In fact I did not find any using of not generic GetHashCode
and Equals
functions at all.
int num = this.comparer.GetHashCode(key) & 2147483647;
for (int i = this.buckets[num % this.buckets.Length]; i >= 0; i = this.entries[i].next)
{
if (this.entries[i].hashCode == num
&& this.comparer.Equals(this.entries[i].key, key))
{
return i;
}
}
So it seems to that my class only needs to implement IEqualityComparer<T>
to be properly used with Dictionary
.
I understand that there will be no harm to implement not generic functions just in case.
But should we spend time if it brings no value?
I will make my question more specific:
Should I implement non-generic GetHashCode
and Equals
if my class implements IEqualityComparer<T>
and:
- I do not use not generic collections in my code
- Third party code does not call
GetHashCode
andEquals
methods of my code.
Does Microsoft code still needs non generic versions to work properly?
Update3:
I think I got it. I thought that IEqualityComparer<T>
is to be implemented inside my class. In that case we would have generic and not generic versions of methods in one place.
That is not how IEqualityComparer<T>
should be used. It should be implemented as separate class and used as parameter.
Thanks to everybody.