Covariance and Contravariance

August 4th, 2008 by Xerxes Leave a reply »

Covariance and Contravariance are terms used in programming languages and set theory to define the behaviour of parameter and return types of a function.

Yes, that’s a mouthful, but in a nutshell:

  • Covariance mandates that the return type and the parameters of a function must be a subtype of the original base class type for any superclass
  • Contravariance allows the return type and/or the parameter types to be super-types of the defined types and not necessarily sub-types

Nothing better than using an example:

   1:  public abstract class Animal
   2:  {
   3:      Animal CreateChild();
   4:  }
   6:  public class Human : Animal
   7:  {
   8:      Animal CreateChild( return new Human(); }
   9:  }
  11:  public class Dog : Animal
  12:  {
  13:      Dog CreateChild( return new Dog(); }
  14:  }

In this example:

  • Animal is a superclass.
  • Human is a subclass of Animal, with a covariant (no change) override to the CreateChild method to return the looser type Animal
  • Dog is a subclass of Animal, with a contravariant override to the CreateChild method to return the stronger type Dog

More reading on Eric Lippert’s blog series on Covariance and Contravariance in C#

EDIT: I thought it best prudent that I clarify that this is only one example of where variance is used. Method signatures, delegates and arrays are some more examples of where the theory of co and contra variance can be found.

Be Sociable, Share!

Comments are closed.