Sunday, January 29, 2012

Covariance and Contravariance in delegates

If you’ve used delegates while programming you probably know about covariance and contravariance in delegates that provide a degree of flexibility when you match method signatures with delegate types.
 
Covariance
Covariance allows a method to have a more derived return type than what is specified in the delegate. This is just another view of polymorphism where you would specify a more generalized delegate that could be used by the objects deriving from the specified type.
 
The following example shows an example where covariance comes into picture.
 
class Fruit    
{    
}    
  
class Apple : Fruit    
{    
}    
  
class CovarianceExample    
{    
    public delegate Fruit CreateFruit();    
  
    public static Fruit CreateGenericFruit()    
    {    
        return new Fruit();    
    }    
  
    public static Apple CreateApple()    
    {    
        return new Apple();    
    }    
  
    public static void Main(string[] args)    
    {    
        CreateFruit fruitCreator = CreateGenericFruit;    
       
        // This is also perfectly fine.    
        CreateFruit appleCreator = CreateApple;    
    }    
}    
  
The delegate CreateFruit defines a return type of type Fruitand the same is applied to a method having the type Apple as a return type.
 
Contravariance
Contravariance allows a method to have parameters that are less derived than what is specified in the delegate type.
 
class ContravarianceExample    
{    
    public delegate void ProcessFruit(Apple myFruit);    
  
    public static void Process(Fruit myFruit)    
    {    
        Console.WriteLine("Fruit Processed.");    
    }    
  
    public static void Main(string[] args)    
    {    
        ProcessFruit processor = Process;    
        
        // Example of contravariance    
        processor(new Apple());    
    }    
}    
 
The above method shows how a delegate is invoked with an argument that is more specialized than the one specified in the delegate.
 
While its not always necessary to remember these terms, it is usually easier to remember these simple concepts when we remember the terms. I knew this was possible but I only came across these terms while browsing through MSDN documentation lately.
 
Although I’m pretty sure almost everyone who’s worked with delegates has come across these terms at least once, I would like to hear from you if this post has filled two more words to your .NET vocab.

No comments:

Post a Comment