Covariance and Contravariance

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:

[HTML1]

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>