From the IEqualityComparer
We recommend that you derive from the EqualityComparer
class instead of
Regarding your first question:
The remarks section for the IEqualityComparer
Looking at the public/protected interface of the EqualityComparer
class, there's only one redeeming quality, it implements the non-generic IEqualityComparer
interface. I think what they meant to say that they recommend deriving from it because EqualityComparer
actually implements the non-generic IEqualityComparer
interface that way your class may be used where the non-generic comparer is required.
It does make more sense in the remarks section for IComparer
We recommend that you derive from the
Comparer
class instead of implementing theIComparer
interface, because theComparer
class provides an explicit interface implementation of theIComparer.Compare
method and theDefault
property that gets the default comparer for the object.
I suspect it was supposed to say something similar for IEqualityComparer
but some ideas were mixed up and ended up with an incomplete description.
Regarding your second question:
A primary goal for the collections found in the library was to be as flexible as possible. One way to get that is to allow custom ways of comparing objects within them by providing a IComparer
or IEqualityComparer
to do the comparisons. It would be much more easier to get an instance of a default comparer when one was not supplied than it is to do the comparisons directly. These comparers in turn could include the logic necessary to call the appropriate comparisons packaged nicely.
e.g., The default comparers can determine whether T
implements IEquatable
and call IEquatable
on the object or otherwise use Object.Equals
. Better encapsulated here in the comparer than it is potentially repeated in the collections code.
Besides, if they wanted to fall back on calling IEquatable
directly, they would have to add a constraint on T
that would make this call possible. Doing so makes it less flexible and negates the benefits of providing the comparer in the first place.