Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Covariance vs. contravariance with respect to class inheritance

What is the meaning of the concepts 'covariance' and 'contravariance'?

Given 2 classes, Animal and Elephant (which inherits from Animal), my understanding is that you would get a run-time errors if you try and put an Elephant into an array of Animals, and this happens because Elephant is "bigger" (more specific) than Animal. But could you place an Animal into an array of Elephant, seeing how Elephant is guaranteed to contain the Animal properties?

like image 588
alexmac Avatar asked Nov 07 '08 15:11

alexmac


2 Answers

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.

like image 133
Bill the Lizard Avatar answered Sep 27 '22 08:09

Bill the Lizard


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

like image 34
MrKurt Avatar answered Sep 24 '22 08:09

MrKurt