CSharp - Contravariance in Delegates


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.


using System;
 delegate void MyDele(Bus v);
class Vehicle/* ww  w . j a  v  a 2  s .c o m*/
    public void ShowVehicle(Vehicle myV)
        Console.WriteLine(" Vehicle.ShowVehicle");
class Bus : Vehicle
    public void ShowBus(Bus myB)

class Program

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


Related Topic