Explain covariance and contra-variance in .NET Framework 4.0. Give an example for each. Ans. 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 to a variable of type IEnumerable where, T1 derives from T2. For example, IEnumerable str1= new List (); IEnumerable str2= str1; Contravariance allows you to assign a variable of Action to a variable of type Action. For example, IComparer obj1 = GetComparer() IComparer 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. - Study24x7
Social learning Network
02 May 2023 12:11 PM study24x7 study24x7

Explain covariance and contra-variance in .NET Framework 4.0. Give an example for each. Ans. 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 ca...

See more

study24x7
Write a comment
Related Questions
500+   more Questions to answer
Most Related Articles