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
3: Animal CreateChild();
6: public class Human : Animal
8: Animal CreateChild( return new Human(); }
11: public class Dog : Animal
13: Dog CreateChild( return new Dog(); }
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.
- Strongly-Typing Your Domain Values I love this one. I don’t know the name of...
- Thread Safety and Locking I was recently reading a post about writing non-threadsafe code...
- Being driven down a path Recently, i’ve been looking more into TDD and mocking in...
- MCMS: GetByGuid throws COMException (“Server Error”) In (the now famous) Project P, working with Microsoft CMS’s...
- Unsatisfied By My Specification Pattern This week, I hit an interesting problem which I don’t...