C# 4.0 is going to support covariance and contravariance. But I don't clearly understand the benefits of this new feature. Can you explain me (clearly) why we need it?
They just allow you to do some things that are conceptually valid, and formally acceptable, but aren't currently allowed because of language constraints. For example:
IEnumerable<int> ints = new List<int> { 1, 2, 3 };
Action<IEnumerable<object>> PrintThings =
x => { foreach(var thing in x) Console.WriteLine(thing); };
PrintThings(ints); // doesn't compile right now :( will compile in 4.0
There's no fundamental reason why this can't work or shouldn't work; it just happens to not be allowed in the language. By allowing it, you make programmers' lives easier when such an operation would be natural for them to perform.
There are alot of misconceptions out there as to how and what will work in 4.0. The best explanation I've read so far was written my Marc Gravell. See his blog post here:
http://marcgravell.blogspot.com/2009/02/what-c-40-covariance-doesn-do.html
Just to reiterate, alot of ppl think this will work in 4.0:
public class Base{}
public class Derived : Base {}
..in some other class
List<Derived> derived....
public void Method(List<Base> b){}
Even in 4.0, you will not be able to pass the List into this method. As Marc points out, that's what Generic constraints are there for, and can be done since 2.0
One of the benefits that, in my opinion, covariance is going to help a lot is with Generics.
I encountered several situations where one needs to explicitly use Cast
to convert a specific type to it's base.
class Foo { }
class Bar : Foo { }
// ...
IEnumerable<Foo> foos = new List<Foo>();
IEnumerable<Bar> bars = new List<Bar>();
foos = bars.Cast<Foo>();
// C# 4.0
foos = bars;
Here's a good reference on the subject.
Bart De Smet has a great blog entry about covariance & contravariance here.