TheChaseMan's Frenetic SoapBox

Always looking for better ways to do things...

C# 2.0 Feature - Covariance

C# has a new feature known as covariance that allows you define a delegate with a return type of a base class that can be used by its derived type. So, if I define a class X and class Y derives from X, I can define a delegate with a return type of X, but I can use the delegate to return type X or Y. In the example below, I define a delegate that returns the base class type Automobile, but I can still use that same delegate to return a derived Car object...

 

using System;

 

class Automobile {

    public Automobile CreateAuto() { return new Automobile(); }

}

 

class Car : Automobile {

    public Car CreateCar() { return new Car(); }

}

 

class Application {

    public delegate Automobile Create();

 

    public static void Foo(Create c) {

        c();

    }

 

    public static void Main() {

        Create c1 = new Create(new Automobile().CreateAuto);

 

        //In VS.NET 2003, the following exception would occur

        //on the next line of code:

        //  "Method 'Car.CreateCar()' does not match delegate

        //'Automobile Application.Create()"

        Create c2 = new Create(new Car().CreateCar);

        Foo(c1);

        Foo(c2);

    }

}


Digg!

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

Feedback

No comments posted yet.