menu

Sunday, September 18, 2016

Covariance & Contravariance

Covariance 
Before .Net 4.0 it was not possible to assign a reference variable of List of parent type to List of its child type.
IEnumerable<Employee> empList = new List<PermanentEmployee>(); X (not possible)
Where PermanentEmployee is child type of Employee type.

But possible in 4.0 on-words by introducing out keyword.

Contravariance
A base type of function pointer (delegate) reference variable was not able to get assign to reference variable of its child type.
delegate void MyPtr<T>(T o);
MyPtr<Employee> oEmp = Print;
MyPtr<PermanentEmployee> oPEmp = oEmp; X (not possible)

But possible in 4.0 on-words by introducing in keyword.
delegate void MyPtr<in T>(T o);

Below is the complete code demonstrating both.
using System;
using System.Collections.Generic;
namespace CovarianceContravariance
{
    class Program
    {
        delegate void MyPtr<in T>(T o);
        static public void Contraveriance()
        {
            MyPtr<Employee> oEmp = Print;
            MyPtr<PermanentEmployee> oPEmp = oEmp; //Backword campatability
        }
        static void Print(Employee emp)
        {
            Console.WriteLine(emp.Name);
        }
        //-------------------------------------------------------------
        public void Coveriance()
        {
            Employee emp = new PermanentEmployee(); //Polymorphism - Valid Statement
            emp = new ContractEmployee(); //Polymorphism - Valid Statement
            //Valid Statement, Invalid below 4.0
            IEnumerable<Employee> empList = new List<PermanentEmployee>();
        }
        //-------------------------------------------------------------
        static void Main(string[] args)
        {
           
        }
    }
    public class Employee
    {
        public string Name = "Animal";
    }
    public class PermanentEmployee : Employee
    {

    }
    public class ContractEmployee : Employee
    {

    }
}

No comments:

Post a Comment