Co-Variance in C#

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. 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4.   
  5. namespace Co_variance
  6. {  
  7.   
  8.     class animal  
  9.     {  
  10.   
  11.     }  
  12.   
  13.     class dog : animal  
  14.     {  
  15.   
  16.     }  
  17.   
  18.     class cat : animal  
  19.     {  
  20.   
  21.     }  
  22.     class Program  
  23.     {  
  24.   
  25.   
  26.         static void Main(string[] args)  
  27.         {  
  28.             //dynamic polymorphism  
  29.             animal objanimal = new dog();  
  30.             objanimal = new cat();  
  31.   
  32.         }  
  33.     }  
  34. }  
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: 
  1. 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.