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);
}
}