Showing posts with label Covariance. Show all posts
Showing posts with label Covariance. Show all posts

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.

Monday, May 25, 2009

Delegate Covariance and Contra-variance in C# 4.0

C# 4.0 introduces co and contra-variance. Consider this code:



The out and in keywords in the delegate definitions above specify the delegates to be co or contra variant. out keyword says that, Child class of T can be used instead of T in Func1 definition. While in keyword specifies that the base class of T can be used instead of T in Action1 definition.
Try to play with this code, and try switching the places of out and in keywords in the above delegate definitions.