Introduction
In this blog, we are discussing the use of co-variance in C#. Both of these are introduced in .NET 4.0. In order to understand the importance of co-variance, we need to create a simple application in .NET 3.0.
Let's create a simple console application using framework 3.0
In the below code, we can see the implementation of inheritance and dynamic polymorphism. we are creating an object for animal class and run time calling cat, in other words, we take the parent object and point to the child object.
- using System;
- using System.Collections.Generic;
- using System.Text;
-
- namespace Co_variance
- {
-
- class animal
- {
-
- }
-
- class dog : animal
- {
-
- }
-
- class cat : animal
- {
-
- }
- class Program
- {
-
-
- static void Main(string[] args)
- {
-
- animal objanimal = new dog();
- objanimal = new cat();
-
- }
- }
- }
We can build this program without any error.
Let me write some more code. If I say animal, I can point towards the dog. In other words, we can use the group of animals to point to the group of dogs.
See the below code so that we can understand:
- IEnumerable<animal> animals = new List<dog>();
In the above snapshot, we can see an explicit type conversion issue. In this case, covariance comes to help.
Now do one thing, just change or update your framework to 4.0 and compile your project and we will not get any errors.
Please check the below snapshot.
Covariance preserves assignment compatibility between the parent and child relationship during the dynamic polymorphism.
Summary
In this blog, we discussed the use of co-variance in C# with a simple example.