views:

697

answers:

3

What are the concepts of covariance and contravariance?

Given 2 classes, Animal and Elephant (which inherits from Animal), my understanding is that you get runtime errors in .NET if you try and put an Elephant into an array of Animal, which happens because Elephant is "bigger" (more specific) than Animal. But could you assign Animal to an array of Elephants as Elephant is guaranteed to contain the Animal properties?

+1  A: 

Have a look at this overview of covariance and contravariance in C# 4.0 and see if that helps:

http://blogs.msdn.com/charlie/archive/2008/10/27/linq-farm-covariance-and-contravariance-in-visual-studio-2010.aspx

MrKurt
+6  A: 

You have it backwards. You can add an Elephant to an Animal array because it is an Animal, and it's guaranteed to have all of the methods an Animal is required to have. You can't add an Animal to an Elephant array because it does not have all of the methods that an Elephant is required to have.

The Wikipedia article on covariance and contravariance has a good explanation of this:

Within the type system of a programming language, an operator from types to types is covariant if it preserves the ordering, ≤, of types, which orders types from more specific ones to more generic ones; it is contravariant if it reverses this ordering. If neither of these apply, the operator is invariant. These terms come from category theory.

Also, you said that type Elephant was "bigger", and this is not the case. Type Animal is "bigger" in the sense that it includes more specific types, such as Elephant, Giraffe, and Lion.

Bill the Lizard
Ah that makes sense so would you would say an Elephant is covariant to an animal but an animal is contravariant to an elephant?
alexmac
It depends on what you're doing with the types. The methods of Elephant need to return the same or narrower type as Animal's methods (they could return Animal or Elephant, if the Animal method returns Animal). That would be called covariant.
Bill the Lizard
But the method parameters of Elephant's methods need to be the same or wider than Animal's methods. This is contravariance.
Bill the Lizard
+2  A: 

This was also discussed here yesterday.

DOK