Skip to main content

Variance in C#.net 4.0 Covariance and Contravariance

Within the type system of a programming language, covariance and contravariance refers to the ordering of types from narrower to wider and their interchangability or equivalence in certain situations (such as parameters, generics, and return types).
  • covariant: converting from narrower (float) to wider (double).
  • contravariant: converting from wider (double) to narrower (float).
  • invariant: Not able to convert (Null).

Concept Of Variance :

If y is derived from X and y relates to X then we can assign X to y. Like X=y. This is Covariance.
If Y is derived from X and y relates to X then we can assign y to X. Like y = X. This is Contravariance.
If class A is related to B then B is related A.
Covariance
Class B: A then we can assign A = B
Contravariance
Class B: A then we can assign B = A

Example

Class String:Object
Covariance => Object=string;
Contravariance=> string=Object;
Covariance interface and delegate must have 'In' keyword declaration for input parameter. Contravariance interface and delegate must have 'Out' keyword declaration for output parameter.

http://www.codeproject.com/KB/cs/CSharpVariance.aspx

Comments