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)
- {
- //dynamic polymorphism
- animal objanimal = new dog();
- objanimal = new cat();
- }
- }
- }
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.

RahulPosted Mar 5, 2020, 5:54 AM
Article may be more helpful, if you post code instead of snapshots.
Hemant MahajanPosted Mar 4, 2020, 2:57 AM
What about List<animal> animals = new List<dog>();
Logesh PalaniPosted Mar 4, 2020, 1:20 AM
Thanks for sharing man, clear explanation
Rajanikant HawaldarPosted Mar 3, 2020, 8:36 PM
Helpful article madan