From the IEqualityComparer<T>
remarks section on MSDN:
We recommend that you derive from the EqualityComparer<T> class instead of implementing the IEqualityComparer<T> interface, because the EqualityComparer<T> class tests for equality using the IEquatable<T>.Equals method instead of the Object.Equals method. ...
I don't understand the quote's argument of why we would should prefer to derive from
EqualityComparer<T>
class instead of implementingIEqualityComparer<T>
. It implies that objects implementingIEqualityComparer<T>
will test for equality usingObject.Equals
, but isn't the whole point of implementingIEqualityComparer<T>
when we don't want to test for equality usingObject.Equals
orIEquatable<T>.Equals
?It also implies that if we derive from
EqualityComparer<T>
, then derived class will test for equality usingIEquatable<T>.Equals
method. Again, isn't the whole point of deriving fromEqualityComparer<T>
when we don't want to test for equality usingObject.Equals
orIEquatable<T>.Equals
(sinceEqualityComparer<T>.Default
already test usingObject.Equals
orIEquatable<T>.Equals
)?
... This is consistent with the Contains, IndexOf, LastIndexOf, and Remove methods of the Dictionary<TKey, TValue> class and other generic collections.
I assume most collections in the .NET library test for default equality of elements (i.e. when users don't provide their own custom
IEqualityComparer<T>
objects to these collections) by callingIEquatable<T>.Equals
orObject.Equals
(depending on whether or not elements of typeT
implementIEquatable<T>
) viaEqualityComparer<T>.Default
.Why don't these collections (when testing for default equality) call
IEquatable<T>.Equals
orObject.Equals
directly instead of viaEqualityComparer<T>.Default
class?