TheChaseMan's Frenetic SoapBox

Always looking for better ways to do things...

Contravariance

As a nice follow-up to my last blog post…

 

C# also has a new feature called “contravariance” which allows you to define a delegate parameter with a derived type which will also allow you to pass types higher up in the inheritance chain. For example, if type X is a base class and type Y derives from X, you can define a delegate with a parameter of type Y and the delegate will also accept type X as a parameter.

 

using System;

 

class Automobile {

    public static void PrintAutoParts(Automobile a) { }

}

 

class Car : Automobile {

    public static void PrintCarParts(Car c) { }

}

 

class Application {

    public delegate void PrintPartsList(Car car);

 

    public static void Foo(PrintPartsList del) {}

 

    public static void Main() {

        PrintPartsList del1 = new PrintPartsList(Automobile.PrintAutoParts);

        PrintPartsList del2 = new PrintPartsList(Car.PrintCarParts);

        Foo(del1);

        Foo(del2);

    }

}


Digg!

posted on Sunday, July 04, 2004 8:52 PM

Feedback

No comments posted yet.