.NET: covariance and contravariance

Possible duplicate:
The difference between covariance and contravariance

I am trying to understand what covariance and contravariance are, as well as the difference between them. I looked at this link , and so far I have understood the following:

Covariance is the process by which you assign a derived member to a base element. For instance:

IEnumerable<Derived> d = new List<Derived>(); IEnumerable<Base> b = d; 

I'm not even sure I'm right about the above ... guess. Basically, I'm looking for someone to omit it for me in the simplest of terms so that I can understand what these two are and the differences between them.

I also understand that there are similar discussion topics, but most of the answers are not the description I was looking for.

+6
source share
1 answer

For our internal workouts, I worked with the wonderful book, Smalltalk, Objects and Design (Chamond Liu), and I paraphrased the following examples. - Hope this helps ...

What does "sequence" mean? The idea is to design type type hierarchies with strongly replaceable types. The key to achieving this consistency is subtype matching. (Here we discuss the Liskov Substitution Principle (LSP) at a high level.)

covariance: Let it be assumed that birds that "lay" eggs in succession lay: If the Bird type lays an egg, will not the subtype of the birds be the subtype of the egg? For instance. the Duck type contains DuckEgg, then consistency is set. Why is this consistent? Because in this expression: Egg anEgg = aBird.Lay(); The aBird link may be legally replaced by a bird or a duck instance. We say that the return type is covariant to the type in which Lay () is defined. Subtype priority may return a more specialized type. => "They deliver more."

contravariance: Suppose that pianists can play "sequentially" with static typification: If a pianist plays the piano, can she play GrandPiano? Will the virtuoso play Gran Piano? (Be careful, there is a twist!) This is inconsistent! Because in this expression: aPiano.Play(aPianist); aPiano cannot be legally replaced by a piano or an instance of GrandPiano! "GrandPiano" can only be played by virtuoso, pianists are too general! GrandPianos should be reproduced by more general types, then the game is consistent. We say that the parameter type is contravariant to the type in which Play () is defined. A wildcard subtype can take on a more general type. => "They require less."

0
source

Source: https://habr.com/ru/post/892447/


All Articles