1
Reply

What is co-variance and contra-variance?

Murali Poola

Murali Poola

12y
3.1k
0
Reply

    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.

    In C#, variance is supported in the following scenarios:

    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)

    Arrays are covariant since C# 1.0. You can always do the following:

    object[] obj = new String[10];

    What is array covariance?

    Arrays are covariant since C# 1.0. You can always do the following:

    object[] obj = new String[10];

    Covariance in arrays is considered “not safe,” because you can also do this:

    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.