Sunday, November 06, 2005

I was playing around with the .NET 2.0 framework a little bit this weekend and a cool new feature I stumbled upon is covariant delegates.

This allows for delegates that have a signature that uses a base class to be used by any delegate method that inherits from the base class used in the delegate signature.

Heres an example:

class Mammals
{
}

class Dogs : Mammals
{
}

class Program
{
   // Define the delegate.
   public  delegate Mammals HandlerMethod();

   public  static Mammals FirstHandler()
   {
      return null;
   }

   public  static Dogs SecondHandler()
   {
      return null;
   }

   static void Main()
   {
      HandlerMethod handler1 = FirstHandler;

      // Covariance allows this delegate.
      HandlerMethod handler2 = SecondHandler;
   }
}

Even though the delegate in the example has a signature that expects a Mammals class as long as the Dog class inherits from the Mammals class, the handler2 delegate method is legal. In the 1.x framework this would not compile and you would get a return types don't match error message.

Learn more here and here.

Sunday, November 06, 2005 9:08:02 PM (GMT Standard Time, UTC+00:00)  #    Comments [0]  | 

Theme design by Jelle Druyts

Pick a theme: