New Features in C# 2.0—Co- and Contravariance: How do I do that?

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:Tutorials
C# Tutorials

New Features in C# 2.0

© 2005 O'Reilly Media, Inc.

How do I do that?

Covariance and contravariance give you more flexibility in the methods you encapsulate in delegates. The use of both covariance and contravariance is illustrated in Example 1-10.


Contravariance allows you to encapsulate a method with a parameter that is of a type from which the declared parameter is directly or indirectly derived.


Example 1-10. Using covariance and contravariance

#region Using directives
 
using System;
using System.Collections.Generic;
using System.Text;
 
#endregion
 
namespace CoAndContravariance
{
  class Mammal
  {
    public virtual Mammal ReturnsMammal( )
    {
      Console.WriteLine("Returning a mammal");
      return this;
    }
  }
 
  class Dog : Mammal
  {
    public Dog ReturnsDog( )
    {
      Console.WriteLine("Returning a dog");
      return this;
    }
  }
 
  class Program
  {
    public delegate Mammal theCovariantDelegate( );
    public delegate void theContravariantDelegate(Dog theDog);
    private static void MyMethodThatTakesAMammal(Mammal theMammal)
    {
      Console.WriteLine("in My Method That Takes A Mammal");
    }
    private static void MyMethodThatTakesADog(Dog theDog)
    {
      Console.WriteLine("in My Method That Takes A Dog");
    }
    static void Main(string[ ] args)
    {
      Mammal m = new Mammal( );
      Dog d = new Dog( );
      theCovariantDelegate myCovariantDelegate =
        new theCovariantDelegate(m.ReturnsMammal);
      myCovariantDelegate( );
      myCovariantDelegate =
        new theCovariantDelegate(d.ReturnsDog);
      myCovariantDelegate( );
      theContravariantDelegate myContravariantDelegate =
        new theContravariantDelegate(MyMethodThatTakesADog);
      myContravariantDelegate(d);
      myContravariantDelegate =
        new theContravariantDelegate(MyMethodThatTakesAMammal);
      myContravariantDelegate(d);
    }
  }
}

Output:

Returning a mammal
Returning a dog
in My Method That Takes A Dog
in My Method That Takes A Mammal


Previous_Page_.gif Next_Page_.gif


Personal tools