#1,142 – Using EqualityComparer to Compare Objects in Generic Types
July 21, 2014 2 Comments
By default, you can’t use equality operators on objects whose type is a type argument within a generic class. If you constrain an argument to be a reference type, you can use equality operators to do reference equality checks. But you can‘t make use of overloaded equality functionality.
You can do a true equality check between objects using the EqualityComparer<T> class. Below is an example. EqualityComparer<T> makes use of overloaded equality logic in the Dog class, even though we haven’t constrained the T argument.
public class Pile<T> { List<T> pile = new List<T>(); EqualityComparer<T> comparer = EqualityComparer<T>.Default; public void Add(T item) { if (!pile.Contains(item)) pile.Add(item); } public bool IsFirst(T item) { // Reference equality only, if we do // where T : class //bool equalStd = (pile[0] == item); // Makes use of overloaded Equality // functionality in T bool equalBetter = comparer.Equals(pile[0], item); return equalBetter; } }