#1,139 – The Problem with Comparisons of Objects in Generic Types

If you don’t constrain a type parameter in a generic class, the compiler will not let you compare two instances of objects of that type using the == or != operators.

In the example below, we store a collection of objects whose type is the type parameter T.  

    public class Pile<T>
    {
        List<T> pile = new List<T>();

        public void Add(T item)
        {
            if (!pile.Contains(item))
                pile.Add(item);
        }

        public bool IsFirst(T item)
        {
            // Compare to null allowed
            bool isnull = (item == null);

            return (pile[0] == item) ;
        }

        public void Dump()
        {
            foreach (T item in pile)
                Console.WriteLine(item);
        }
    }

If we try compiling this code, we’ll get a compile-time error in the IsFirst method, indicating that we can’t apply the == operator.  The compiler doesn’t have enough information about the type T to know that we can use the == operator.
1139-002

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

5 Responses to #1,139 – The Problem with Comparisons of Objects in Generic Types

  1. Pingback: Dew Drop – July 16, 2014 (#1815) | Morning Dew

  2. Not sure if you’re doing this for educational purposes but you should never have to `… ? true : false` in production code. The expression to the left of the `?` already returns true/false.

  3. Sorry, should have mentioned, I’m 90% sure you can still do `Object.ReferenceEquals(pile[0], item)` if you simply want a reference comparison. I also think you can probably do == if item is dynamic, but I’m less sure of that one.

  4. Pingback: #1,140 – Comparing Reference-Typed Objects in Generic Types | 2,000 Things You Should Know About C#

Leave a comment