#1,142 – Using EqualityComparer to Compare Objects in Generic Types

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;
        }
    }

1142-001

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #1,142 – Using EqualityComparer to Compare Objects in Generic Types

  1. Pingback: Dew Drop – July 21, 2014 (#1818) | Morning Dew

  2. Pingback: Tools Of The Trade - The Daily Six Pack: July 22, 2014

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: