Tuesday, May 26, 2009

C# 4.0 Generics and Variance

Yesterday I blogged about using the variance with delegates. Today I will expand that discussion to the Generics. In C# 3.0, arrays are co-variant, meaning array of a child class is also an array of its base class. e.g.
string[] astr = new string[] {"a", "b", "cde" };
object[] aobj = astr;
There was no support for generic variance.
C# 4.0 introduces covariance and contra variance. And changes the definition of IEnumerable to IEnumerable<out T>. The <out T> specifies that if there is a method which takes Enumerable, then the programmer can also pass the IEnumerable<"Derived class of T">. Consider this code:

PlayAll method takes an IEnumerable and two calls to this method inside main work well even we pass IEnumerable and IEnumerable. Because IEnumerable is covariant, so it is legal to pass any derived types IEnumerable where a base class IEnumerable is required.

No comments:

Post a Comment