Saturday, 27 August 2016

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.
class Animal 

        public virtual int Get2 
        public virtual void Get1() 
Create a child class as Dog, which inherits base class as Animal.
class Dog : Animal 

        public int num; 
        public Dog(){} 
        public Dog(int a) 
            num = a; 
        public override int Get2 
            get { return num; } 
        public override void Get1() 
Create a Program class to create an instance and to explain about Covariance.
class Program   
        static void Main(string[] args)   
            Animal objAnimal = new Dog();   
Note: objAnimal object is a valid statement in .NET framework 3.5 because the child class points to the base class object.          
Dog ob1 = new Dog(1); 
           Dog ob2 = new Dog(2); 
           Dog ob3 = new Dog(3); 
           Dog ob4 = new Dog(4); 
           List<Dog> list = new List<Dog>(); 
           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.

No comments :