CSharp - Contravariance in Delegates

Introduction

Contravariance is related to parameters.

Suppose that a delegate can point to a method that accepts a derived type parameter.

With the help of contravariance, we can use the same delegate to point to a method that accepts a base type parameter.

delegate MyDele, expects a method that accepts a bus (derived) object parameter, yet it can point to a method that accepts vehicle as a (base) object parameter.

Demo

using System;
 delegate void MyDele(Bus v);
class Vehicle//  ww  w  .  ja  v  a2s .  c om
{
    public void ShowVehicle(Vehicle myV)
    {
        Console.WriteLine(" Vehicle.ShowVehicle");
    }
}
class Bus : Vehicle
{
    public void ShowBus(Bus myB)
    {
        Console.WriteLine("Bus.ShowBus");
    }
}

class Program
{

    static void Main(string[] args)
    {
        Vehicle vehicle1 = new Vehicle();//ok
        Bus bus1 = new Bus();//ok
                             //General case
        MyDele del1 = bus1.ShowBus;
        del1(bus1);
        //Special case:
        //Contravariance:
        MyDele del2 = vehicle1.ShowVehicle;
        del2(bus1);
        //you cannot pass vehicle object here
        //del2(vehicle1);//error
    }
}

Result

Related Topic