2

Possible Duplicates:
Covariance and contravariance real world example
still confused about covariance and contravariance & in/out

Can you give me a description or example of both covariance and contravaiance, and why they now decided to add it to .NET 4?

Community
  • 1
  • 1
JoshVarga
  • 685
  • 3
  • 10
  • This may help: http://stackoverflow.com/questions/245607/how-is-generic-covariance-contra-variance-implemented-in-c-4-0 – Arseni Mourzenko Aug 31 '10 at 02:34
  • 5
    Also http://stackoverflow.com/questions/2662369/covariance-and-contravariance-real-world-example and http://stackoverflow.com/questions/1163465/covariance-and-contravariance-in-programming-languages and http://stackoverflow.com/questions/3445631/still-confused-about-covariance-and-contravariance-in-out ...hell ..just enter both terms in search box...easier that way – Jagmag Aug 31 '10 at 02:37
  • Ok, cool this should give me something to read for a bit. I am trying to get a high-level summary, and also how I can implement co/contravariance in my own app. – JoshVarga Aug 31 '10 at 02:43
  • 1
    You might also want to read the twenty or so articles I've written on the subject of how we designed and implemented variance. http://blogs.msdn.com/b/ericlippert/archive/tags/covariance+and+contravariance/ – Eric Lippert Aug 31 '10 at 05:58

2 Answers2

2

If B inherits from A, ie is a subtype of A, then C function is covariant if C(B) is a subtype of C(A), contravariant if C(A) is a subtype of C(B).

The question is wether or not you want consumers to deal with supertypes or subtypes.

A common example is a class library dealing in fruit classes.

It is OK for me to give you an apple where you expect a fruit. It is not OK for me to give you just any fruit where you expect an apple.

If you were making a fruit library. You should be expecting instances fruit from me and I should be expecting instances of fruit from you. Neither of us should have expectations about a subtype that could be false.

Therefore, the answer to the question above depends on wether you're getting or sending. Wether the parameter is read or write. A fruit list should be accepting bananas or apples, but only send "fruits"

Tormod
  • 4,551
  • 2
  • 28
  • 50
0

Since there is no answer given I just summarize the comments

stackoverflow.com/questions/245607/ – MainMa

stackoverflow.com/questions/2662369/ stackoverflow.com/questions/1163465/ stackoverflow.com/questions/3445631/ – In Sane 56 mins ago

JoshVarga
  • 685
  • 3
  • 10