Wednesday, November 3, 2010

Covariance and Contravariance in C# 4.0

Variance is about being able to use an object of one type as if it were another, in a type-safe way. Variance comes into play in delegates and interfaces and are not supported for generic and non generic classes.
public class Person {}
public class Customer : Person {}
Covariance is about values being returned from an operation back to the caller. In the following example, the keyword out is used with generic parameter to support covariance. Contravariance is about values being passed in using keyword in.

delegate T MyFunc<out T>(); 

MyFunc<Customer> customer = () => new Customer();

// Converts using covariance - narrower type to wider type assignment 
MyFunc<Person> person = customer; 
delegate void MyAction<in T>(T t);

MyAction<Person> printPerson = (person)=> Console.WriteLine(person);

// converts using contravariance - assignment from a wider type to a narrower type
MyAction<Customer> printCustomer = printPerson;

No comments: