Type Variance

In C# 4.0 you can notate a generic interface or delegate indicating whether it supports covariance or contravariance.
This only applies to constructed types in which reference types are passed for the type arguments to the generic type.


Variance is all about convertibility
Variance is a feature that is often taken for granted Variance is all about convertibility
When we talk about variance we need to think about the relationships between two types
There are four possible relationships that can exist between two objects

  • Type A is smaller (or narrower) than Type B

  • Type A is larger (or wider) than Type B

  • Type A is equal to Type B

  • Type A and Type B are completely different


Interface Types can hold objects of various types as long as they implement the interface Base Classes can hold objects of various types as long as they derive from the base class



What does covariance mean -
What does contravariance mean - an inverted covariant relationship


There are two new keywords that have been introduced to allow you to indicate if covariance and contravariance is supported These extensions only work with interfaces and delegates "out" for covariance "in" for contravariance



Array covariance

string[] mystrings = new string[] {"one","two","three"}; 
object[] myobjects = mystrings;
//both strings and objects are reference type variables

The following line of code does not work and generates a ArrayTypeMismatchException

myobjects[1] = new object(); 


Generic list variance

List<string> mystrings = new List<string> {"one","two","three"}; 
List<object> myobjects = mystrings;
//the second line of this will generate a compilation error



© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext