C# is an Object-oriented programming language. C# comes with simplicity, expressiveness and great performance to meet the programmer productivity.
So far, we have studied about variance
. Now, let's study co-variance and contra-variance with different types in this chapter.
The main objective of this article is to learn co-variance and contra-variance in C# programming
Co-variance and Contra-variance
Co-variance and Contra-variance are the C# terms which enables the implicit reference conversion for delegates
and generic types
Meanwhile Co-variance preserves the assignment compatibility and Contra-variance reverses the Co-variance functionality.
Assignment compatibility is the concept which provides to store a value of one particular type into the storage location of another type (different than first one) without losing the data.
string Name = "Krishna";
object obj = Name; // Assigning
In the above example, it is clearly explained that an object of more derived type is assigned to a less derived type's object.
Now observe the below lines of code which demonstrates co-variance,
IEnumerable<string> Names = new List<string>();
IEnumerable<object> objs = Names;
In the above lines, the object instantiated with more derived type is assigned to the object instantiated with less derived type. This is called Co-variance
static void MyObj(object ob)
// static method
static void Main()
Action<object> ConObj = MyObj;
Action<string> ConName = ConObj;
In the above code, we have a static method in our class for that we have instantiated a less derived object. Here, we are assigning the object of less derived type to the object of more derived type. This is called as Contra-variance
. This is exactly opposite (reverse) to Co-variance
Note: The above seen codes are the examples of Co-variance and Contra-variance for generic types.
Co-variance for Arrays
In order to do implicit conversion from an array of more derived type to an array of less derived type, Array Co-variance is needed.
object MyArray = new String; // run-time error
The above line will not give any compile time error. But if you run, it will through a run-time error. It is stated that array co-variance is not safe at all. For instance,
MyArray = 3;
This statement causes an ArrayTypeMismatchException
. This is because our MyArray
variable is holding the reference of a string array.
Similar to the co-variance, contra-variance is the reverse functionality of co-variance.
Co-variance for Delegates
Similar to arrays, delegate co-variance allows a method that has parameter types more derived than the specified type in the delegate.
static string MyString()
static void Main()
Func<object> delObj = MyString;
In the above code, we are implementing the conversion of more derived type to less derived type.
Contra-variance means the reverse functionality of above code.
In this article, we have studied about co-variance and contra-variance in C#. Hope you understand.
Thanks for reading,