#1,139 – The Problem with Comparisons of Objects in Generic Types
July 16, 2014 5 Comments
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.
Pingback: Dew Drop – July 16, 2014 (#1815) | Morning Dew
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.
Thanks George, good point. Brain fart on my part.
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.
Pingback: #1,140 – Comparing Reference-Typed Objects in Generic Types | 2,000 Things You Should Know About C#