Covariance and Contravariance. What do they mean again?
I don’t have to deal with covariance and contravariance very often, so every time I do I forget which is which. So, just for my own benefit, here is a note describing them:
Covariance and contravariance are terms that refer to the ability to use a less derived or more derived type than originally specified.
Covariance – Enables you to use a more specific type than originally specified
E.g., in generics
We have a base type called “Feline” and we have a derived type called “HouseCat”.
IEnumerable<HouseCat> cats = new List<HouseCat>();
IEnumerable<Feline> gods = cats;
//Note: felines have a very high opinion of themselves :)
Contravariance – Enables you to use a less derived type than originally specified.
E.g., in generics
Using the same base and derived types as above.
IEnumerable<Feline> gods = new List<Feiline>();
IEnumerable<HouseCat> cats = gods;
References:
Covariance and Contravariance (C# and Visual Basic)
Covariance and Contravariance in Generics
Reblogged this on iReadable.
Elliot Balynn
January 19, 2015 at 2:47 pm