1) Are the reasons why IEqualityComparer<T> was introduced:
a) so we would be able to compare objects (of particular type) for equality in as many different ways as needed
b) and by having a standard interface for implementing a custom equality comparison, chances are that much greater that third party classes will accept this interface as a parameter and by that allow us to inject into these classes equality comparison behavior via objects implementing IEqualityComparer<T>
2) I assume IEqualityComparer<T> should not be implemented on type T that we’re trying to compare for equality, but instead we should implement it on helper class(es)?
Thank you
I’m doubtful that anyone here will be able to answer with any authority the reason that the interface was introduced (my guess–and that’s all it is–would be to support one of the generic set types like
Dictionary<TKey, TValue>orHashSet<T>), but its purpose is clear:If you combine this with the fact you can have multiple types implementing this interface (see
StringComparer), then the answer to question a is yes.The reason for this is threefold:
==) are not polymorphic; if the type is upcasted to a higher level than where the type-specific comparison logic is defined, then you’ll end up performing a reference comparison rather than using the logic within the==operator.Equals()requires at least one valid reference and can provide different logic depending on whether it’s called on the first or second value (one could be more derived and override the logic of the other).==orEquals. This means that any container (likeDictionary<string, T>orHashSet<string>) would be case-sensitive. Allowing the user to provide another type that implementsIEqualityComparer<string>means that the user can use whatever logic they like to determine if one string equals the other, including ignoring case.As for question b, probably, though I wouldn’t be surprised if this wasn’t high on the list of priorities.
For your final question, I’d say that’s generally true. While there’s nothing stopping you from doing so, it is confusing to think that type
Twould provide custom comparison logic that is different from that provided on typeTjust because it’s referenced as anIEqualiltyComparer<T>.