Co-variance and Contra-variance in C#

Goud.Kv
Posted by in C# category on for Intermediate level | Points: 250 | Views : 3003 red flag
Rating: 5 out of 5  
 1 vote(s)

C# is an Object-oriented programming language. C# comes with simplicity, expressiveness and great performance to meet the programmer productivity.
Recommendation
Read Variance in generic types of C# before this article.

Introduction

So far, we have studied about variance in C#. Now, let's study co-variance and contra-variance with different types in this chapter.

Objective

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, arrays and generic types

In other words, these two are the polymorphism extension to the delegates, arrays and generic types.

Meanwhile Co-variance preserves the assignment compatibility and Contra-variance reverses the Co-variance functionality.


Assignment Compatibility:
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.

Example:
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.

And,
class Program
{
    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.

Example,
object[] MyArray = new String[5]; // 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[0] = 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.

Example,
static string MyString()
{
    return "Hello";
}

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.

Conclusion

In this article, we have studied about co-variance and contra-variance in C#. Hope you understand.

Thanks for reading,

Regards,
Krishna.

Page copy protected against web site content infringement by Copyscape

About the Author

Goud.Kv
Full Name: Krishna Vamshi Goud
Member Level: Gold
Member Status: Member,MVP
Member Since: 2/12/2014 2:34:09 AM
Country: India
Thanks & Regards, Krishna


Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)