#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))

        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)

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.


About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: