Explain covariance and contra-variance in .NET Framework 4.0. Give an example for each.

Answer

In .NET 4.0, the CLR supports covariance and contravariance of types in generic interfaces and delegates. Covariance enables you to cast a generic type to its base types, that is, you can assign a instance of type IEnumerable<Tl> to a variable of type IEnumerable<T2> where, T1 derives from T2. For example,

IEnumerable<string> str1= new List<string> ();
IEnumerable<object> str2= str1;


Contravariance allows you to assign a variable of Action<base> to a variable of type Action<derived>. For example,

IComparer<object> obj1 = GetComparer() 
IComparer<string> obj2 = obj1;


.NET framework 4.0 uses some language keywords (out and in) to annotate covariance and contra-variance. Out is used for covariance, while in is used for contra-variance.

Variance can be applied only to reference types, generic interfaces, and generic delegates. These cannot be applied to value types and generic types.

All .net Questions

Ask your interview questions on net

Write Your comment or Questions if you want the answers on net from net Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---