CSharp - Contravariance with Generic Delegates

Description

Contravariance with Generic Delegates

Demo

using System;

//A generic delegate
delegate void aDelegateMethod<in T>(T t);
class Vehicle/*from   w  w w  .  j  a v a2 s. c  o  m*/
{
    public virtual void ShowMe()
    {
        Console.WriteLine(" Vehicle.ShowMe()");
    }
}
class Bus : Vehicle
{
    public override void ShowMe()
    {
        Console.WriteLine(" Bus.ShowMe()");
    }
}
class Program
{
    static void Main(string[] args)
    {
        Vehicle obVehicle = new Vehicle();
        Bus obBus = new Bus();
        aDelegateMethod<Vehicle> delVehicle = ShowVehicleType;
        delVehicle(obVehicle);
        //Contravariance with Delegate
        //Using less derived type to more derived type
        aDelegateMethod<Bus> delChild = ShowVehicleType;
        delChild(obBus);
        Console.ReadKey();
    }

    private static void ShowVehicleType(Vehicle p)
    {
        p.ShowMe();
    }
}

Result

Related Topic