Covariance In C#

What is Covariance?

Covariance is a Polymorphism extension to the arrays, delegates and generics. It provides an implicit reference conversion for arrays, delegates and generic parameter types. Covariance preserves the assignment compatibility.
 
Explanation of Covariance
 
Create a base class as an Animal.
  1. class Animal  
  2. {  
  3.         public virtual int Get2  
  4.         {  
  5.             set;  
  6.             get;  
  7.         }  
  8.         public virtual void Get1()  
  9.         {  
  10.             Console.WriteLine("Animal");  
  11.         }  
  12. }   
Create a child class as Dog, which inherits base class as Animal.
  1. class Dog : Animal  
  2. {  
  3.         public int num;  
  4.         public Dog(){}  
  5.         public Dog(int a)  
  6.         {  
  7.             num = a;  
  8.         }  
  9.         public override int Get2  
  10.         {  
  11.             get { return num; }  
  12.         }  
  13.         public override void Get1()  
  14.         {  
  15.             Console.WriteLine("Dog");  
  16.         }  
  17. }   
Create a Program class to create an instance and to explain about Covariance.
  1. class Program    
  2. {    
  3.         static void Main(string[] args)    
  4.         {    
  5.            
  6.             Animal objAnimal = new Dog();    
  7.         }  
  8. }   
Note: objAnimal object is a valid statement in .NET framework 3.5 because the child class points to the base class object.           
  1. Dog ob1 = new Dog(1);  
  2.            Dog ob2 = new Dog(2);  
  3.            Dog ob3 = new Dog(3);  
  4.            Dog ob4 = new Dog(4);  
  5.   
  6.            List<Dog> list = new List<Dog>();  
  7.   
  8.            list.Add(ob1);  
  9.            list.Add(ob2);  
  10.            list.Add(ob3);  
  11.            list.Add(ob4);  
  12.   
  13.            IEnumerable<Animal> obAnimal = new List<Dog>();   
Note:  object obAnimal of IEnumerable generic interface will throw an error in .NET framework 3.5 because in this object, the list of Dog class tries to point to the list of Animal class.
 
This statement is correct with .NET framework 4.0 because IEnumerable interface is in .NET framework 4.0 default Covariance enabled. 
 
That's it. Thank you. For any suggestions and code clarification, please leave a comment.
Ebook Download
View all
Learn
View all