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!

Related posts:

  1. Strongly-Typing Your Domain Values I love this one. I don’t know the name of...
  2. Thread Safety and Locking I was recently reading a post about writing non-threadsafe code...
  3. Being driven down a path Recently, i’ve been looking more into TDD and mocking in...
  4. MCMS: GetByGuid throws COMException (“Server Error”) In (the now famous) Project P, working with Microsoft CMS’s...
  5. Unsatisfied By My Specification Pattern This week, I hit an interesting problem which I don’t...

Comments are closed.