DEV Community

Contravariance in the real world

Vitor Nunes on August 12, 2018

Contravariance hurts the brain! The definition is straightforward, but applying it to the real world doesn’t make much sense. How come Container[Wa...
Collapse
 
courier10pt profile image
Bob van Hoove

Thanks for bringing this up, it never quite stuck with me.

Here's a C# example using the 'accepts' phrasing:

// Covariant:
//
//         generic    (accepts)   specific
//
IEnumerable<object> objects = new string[] { "a", "b", "c" }; 


// Contravariant:
//
//    specific      (accepts)       generic
//
Action<string> printIt = new Action<object>(o => Console.WriteLine(o));

Pretty much copied from MSDN : Covariance and Contravariance FAQ

Collapse
 
vitornovictor profile image
Vitor Nunes

I'm glad it helped :)
Thanks for sharing this example!

Collapse
 
tenhobi profile image
Honza Bittner

This article helped me A LOT! Thanks. Awesome example.

Collapse
 
toniogela profile image
Antonio Gelameris

Brilliant!

Collapse
 
theodesp profile image
Theofanis Despoudis

Epic I think that made it clear