views:

139

answers:

1

I wish to get acquainted with the recently release of the .NET Framework 4.0 and its Covariance and Contravariance in Generics.

Even though I have read what is written at the referenced link, I can't get a grab on how it should be used, and when it shouldn't.

A brief explanation and a simple real-world-like code sample is appreciated.

Thanks! =)

+3  A: 

Eric Meijer was talking to Scott Hanselman about the Reactive Framework in one of Scott's recent podcasts, and one of the things that Eric said was that, in .NET 4.0, IEnumerable is covariant, but in .NET 3.5 IEnumerable is not.

What this means is that, if you have a Banana object that inherits from Fruit, you can assign the banana to a Fruit variable, but you cannot pass an IEnumerable of bananas to a method expecting a fruit IEnumerable in .NET 3.5, because IEnumerable is not covariant.

From the podcast:

If I have an array of bananas, I can post that where you need an array of fruit because banana is a sub-type of fruit so if I have an array of bananas and you need an array of fruit I can pass you that array. Now, if you expect an enumerable of fruit, I cannot pass you an enumerable of bananas because enumerable until .NET 4.0 was not covariant. So the fact that even though banana is a special kind of fruit, an enumerable of banana was not an enumerable of fruit.

Robert Harvey
Not really a super real-world example, ey? :)
cwap
@cwap: Being able to pass a covariant collection is a genuine programming concern; in one case you can just pass the collection, in the other case, you must copy each item in the collection to a new collection. If you really want the real-world example, listen to the podcast. Eric explains in detail why this was important when designing the Reactive Framework.
Robert Harvey
@Robert Harvey: Granted, didn't listen to the podcast :) At first glance I just didn't think that Banana : Fruit, was that great of a real world example - But we do agree that it's a great feature!
cwap