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

 

Advertisements

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.

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

  1. Pingback: Dew Drop – July 18, 2014 (#1817) | Morning Dew

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: