What is Variance in Generic Types?
Variance is nothing but a discrepancy or conflict happening in the normal behavior. Assume that you have a generic type to which object is passed as type. To a generic type holding objects, can you assign strings? Logically speaking, you can do it since strings are also objects. But you cannot do such assignments. They will end in exception. This is because generic types are invariant by default. However the same scenario is acceptable in arraylist, because arraylist is covariant. But still you can make generic types behave as covariant by performing some workarounds.
This article discusses about few such variance occurrences in generic types and the workaround solution for accomplishing them. It doesnt stop with that, C# version 4.0 permits generic types to be both co-variant and contra-variant. You will also learn about how to implement them.
How Do You Establish Variance in Generic Types of Earlier Versions of C#?
This is not legal because string elements cannot be added to an integer list. To avoid such code, you enforce the constraint. Inside the Add method, you fetch each element of List1 and insert it into List2. This method is generic and you can pass any different type combinations to it. In Main() method, you have called the Add function twice. First time you add intList elements to objList and the second time you add stringList elements to objList. You deal with different types but use the same function. That is the specialty of using generics.
You go with this round about solutions because earlier versions of C# define generic types as invariant. But C# version 4.0 allows generic types to be co-variant as well as contra-variant. Do these terms sound new to you? In the examples discussed so far, you try to assign elements of a sub-type list to the base type. This is termed as co-variance. Contra-variance is the reverse process of co-variance. C# 4.0 supports both of them and hence you need not try with work arounds any more.
How Do You Establish Co-Variance in Generic Types of C# version 4.0?
In this example, you try to convert the in parameter type int of sampleGeneric<int, int> to sampleGeneric<object, int>. You cannot establish co-variance on in parameters. Hence it will not compile. However in the next line of code, you try to convert sampleGeneric<int, int> to sampleGeneric<int, object>. The second parameter of sampleGeneric is an out parameter. In case of out parameter, an int is compatible with object. That is permissible and therefore this line of code is legal.
How Do You Establish Contra-Variance in Generic Types of C# version 4.0?
You can now use IComparer<object> to compare integers or strings.