public void Foo (IEnumerable<object> objects)
{
}
var strings = new List<string>{"first", "second", "third"};
Foo(strings); // Compilation Error.
Foo(strings.Cast<object>()); // O.k.
- Why the first call to Foo doesn’t compile? string derived from object.
- If I can cast the list to object and it’s compiled, why the compiler doesn’t do it by his own?
The first call compiles in .NET 4.0.
In previous versions, the generic types have to match exactly.
I suggest reading the blogs posts of Eric Lippert regarding variance (covariance and contravariance).