#1,068 – Generic IEnumerable Interface Is Covariant
April 4, 2014 1 Comment
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 T 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;