Wednesday, June 22, 2011

Covariance and Contravariance support in .NET 4

According to Wikipedia,  in multilinear algebra and tensor analysis
"covariance and contravariance describe how the quantitative description of certain geometrical or physical entities changes when passing from one coordinate system to another"

Covariance By Example

If there is inheritance relationship, Employee base and Manager derived one, then there’s an implicit reference conversion from Manager to Employee
Manager → Employee
Then Covariance allows implicit conversion of generic types to the base types like
IEnumerable<Manager> → IEnumerable<Employee>
Since both arrows are in same direction means Covariance
Covariant in T: if the ordering of the constructed types follows the ordering of the generic type parameters

Contravariance By Example

Then Covariance allows implicit conversion of generic types to the derived types like
IComparable<Manager> ← IComparable<Employee>
Since both arrows are reversed means Contravariance
Covariant in T: if the ordering of the constructed types is reversed from the ordering of the generic type parameters

out keyword

Out keyword - readonly
the generic type parameter can only appear in output positions — read-only properties and method return values.
IEnumerable<Manager> ms = GetManagers();
IEnumerable<Employee> es = ms; //possible in c#4 only
T is covariant means you only get a Manager out of the sequence, and you never put one in

      in keyword

In keyword - writeonly
The generic type parameter can only be used in input positions — write-only properties and method non-ref and non-out parameters.
IEnumerable<Manager> ms = GetManagers();
IEnumerable<Employee> es = ms; //possible in c#4 only
Vs.
IComparable<Employee> ec = GetEmployeeComparer();
IComparable<Manager> mc = ec; //possible in c#4 only
T is contravariant means because a manager is an employee, putting a manager in EmployeeComparer should work, and it does.

To get more details please download following presentation:

No comments:

Post a Comment