In C#, covariance and
contravariance enable implicit reference conversion for array types, delegate
types, and generic type arguments.Covariance preserves assignment
compatibility and
contravariance reverses it.
1. Covariance in arrays
(since C# 1.0)
2. Covariance and
contravariance in delegates, also known as “method group variance” (since C#
2.0)
3. Variance for generic
type parameters in interfaces and delegates (since C# 4.0)
object[] obj = new String[10];
Arrays are covariant
since C# 1.0. You can always do the following:
object[] obj = new String[10];
obj[0] = 5;
This code compiles, but it throws an exception at run time because obj is in fact an array of strings and cannot contain integers.
