Translate

Tuesday, September 3, 2013

Delegate Covariance and Contravariance C#

Covariance: (Return type of Method is more specific than that of the delegate)

A method targeted by the delegate can return a derived type, of the type expected by the delegate. For example the delegate expects an animal back and it gets back a dog. This is called covariance.

using System;

namespace ContravarianceExample
{
    class Program
    {
        public delegate Animal ADelegate();

        static void Main(string[] args)
        {
            ADelegate del = GiveDog;

            var  animal= del();
            Console.WriteLine(animal.GetType());//Dog
        }

        static Dog  GiveDog()
        {
            return new Dog();
        }


    }

    public class Animal
    {

    }

    public class Dog : Animal
    {

    }


}




Contravariance:(Input paramater of delegate is more specific than that of the method)

As given in here , a delegate can have more specific parameter types than its method target. For example the method targeted by the delegate expects an animal but the delegate input parameter is a dog.This is called contravariance.

using System;

namespace ContravarianceExample
{
    class Program
    {
        public delegate void ADelegate(Dog d);

        static void Main(string[] args)
        {
            ADelegate del = MyMethod;

            del(new Dog());//Dog is a specific kind of Animal
        }

        static void  MyMethod(Animal A)
        {
            Console.WriteLine(A.GetType());//Dog
        }


    }

    public class Animal
    {

    }

    public class Dog : Animal
    {

    }


}


No comments:

Post a Comment

Comments will appear once they have been approved by the moderator