#1,141 – Reference Equality Used Even when Overload Available for Typed Parameter

If a type parameter in a generic class is constrained to be a reference type, using the class designator, then the == and != operators used for this type parameter will perform a check for reference type equality.  This is true even when the type provides a more intelligent equality check by overloading the == operator.

Assume that we overload == for the Dog type to do an intelligent equality check.

            Dog d = new Dog("Jack", 5);
            Dog d2 = new Dog("Jack", 5);

            // sameDog will be true
            bool sameDog = (d == d2);

Below, the == operator performs a reference type equality check on the type parameter.

    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)
        {
            // Reference equality, even if
            // == operator is overloaded in T
            return (pile[0] == item);
        }

Using the above class:

            Pile<Dog> pack = new Pile<Dog>();
            pack.Add(new Dog("Jack", 5));

            Dog d2 = new Dog("Jack", 5);

            // Returns false
            bool sameDog = pack.IsFirst(d2);

 

Advertisement