#1,140 – Comparing Reference-Typed Objects in Generic Types

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

1140-001

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #1,140 – Comparing Reference-Typed Objects in Generic Types

  1. Pingback: Dew Drop – July 17, 2014 (#1816) | 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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s

%d bloggers like this: