#1,140 – Comparing Reference-Typed Objects in Generic Types
July 17, 2014 1 Comment
You can’t normally use the == or != operators on objects whose type is one of the type parameters in a generic class. The compiler doesn’t know enough about the type to be able to use the equality or inequality operators.
If you add a class constraint on a type parameter, indicating that it must be a reference type, then you can use the == and != operators to do basic reference type equality.
public class Pile<T> where T : class { List<T> pile = new List<T>(); public void Add(T item) { if (!pile.Contains(item)) pile.Add(item); } public bool IsFirst(T item) { return (pile[0] == item); } }
Our IsFirst method returns true if the item parameter is the same object as the first item in the collection.
Pile<Dog> pack = new Pile<Dog>(); Dog d1 = new Dog("Bowser"); Dog d1B = new Dog("Bowser"); pack.Add(d1); Console.WriteLine(pack.IsFirst(d1)); Console.WriteLine(pack.IsFirst(d1B));