TechyMedia

A .NET Technology blog | .NET,C# Progamming,C# tutorials,WPF WCF|Software Engineer

NAVIGATION - SEARCH

C# 2.0, Covariance And Contravariance In Delegates

Basic rule of thumb for a delegates is that the referenced method’s argument types and return type should match the delegate’s argument types and return types.But this rule is little relaxed with the covariance-contravariance support for delegates.

In C# there was support for Covariance in arrays from C# version 1.0 itself. With C# 2.0 release the support for  covariance and contravariance has extended to delegates also.

Basic rule of thumb for a delegates is that the referenced method’s argument types and return type should match the delegate’s argument types and return types.But this rule is little relaxed with the covariance-contravariance support for delegates.

Covariance basically means that the argument type of the method that is referenced by a delegate can have argument type different from the delegate return type provided the argument type of the method is a subclass(derived) of the argument type of the delegate.

Contravariance means that the argument type of the method that is referenced by a delegate can have argument type different from the delegate return type provided the argument type of the delegate is a subclass(derived) of the argument type of the method.

See the code sample below for more clarity.

Here below two classes defined.One derived from the other

//base class 
public class Shape 
{

} 

//A derived class 
public class Rectangle : Shape
{

 } 

 Covariance

//Delegate with return type as base class
 public delegate Shape delgateCovariance();

//Method with return type as base class
 public Shape Method1()
 {
       return new Shape();
 }

 //Method with return type as derived class
 public Rectangle Method2()
 {
      return new Rectangle();
 }

Usage is :
delegateCovariance delgate1 = Method1;
delegateCOvariance delegate2 = Method2;

 Contravariance

//Delegate with return type as base class

public delegate void delgateContravariance(Rectangle rect);

 

 //Method with base type as parameter   

public void Method1(Shape shape
{
}

 //Method with derived type as parameter
 public void Method2(Rectangle rectangle)
{
}


Usage is :

delegateContravariance delgate1 = Method1;

delegateContravariance delegate2 = Method2;

 

 Friends Assemby In C#

Pingbacks and trackbacks (1)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading