#1,068 – Generic IEnumerable Interface Is Covariant

A covariant generic interface is one that allows an assignment from a constructed version of the interface on a derived class to a constructed version of the interface for a base class.

For example:

            // If herders is (or implements) IFirstAndLast<BorderCollie>:
            IFirstAndLast<Dog> dogLine = herders;

The IEnumerable<T> interface in System.Collections.Generic is covariant.  This means that you can assign a collection of a given type to an IEnumerable<T> where the represents a type further up the inheritance chain.

For example:

            List<BorderCollie> someBCs = new List<BorderCollie> {
                new BorderCollie("Shep"),
                new BorderCollie("Kirby")

            // Because BorderCollie derives from Dog,
            // we can do the following
            IEnumerable<Dog> dogList = someBCs;

If MerleBorderCollie inherits from BorderCollie, which in turn inherits from Dog, we can also do:

            List<MerleBorderCollie> merles = new List<MerleBorderCollie>
                new MerleBorderCollie("Lady")
            IEnumerable<Dog> moredogs = merles;

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

One Response to #1,068 – Generic IEnumerable Interface Is Covariant

  1. Pingback: Dew Drop – April 4, 2014 (#1758) | 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 )

Connecting to %s

%d bloggers like this: