Reputation: 8199
I have:
interface IEntry {}
class Entry : IEntry {}
Why is it that I cannot do this?
IEnumerable<IEntry> func()
{
return new List<Entry>();
}
Doesn't the returned object satisfy all the type requirements?
Upvotes: 1
Views: 141
Reputation: 98826
C# (and .Net) 4.0 introduced the concept of covariance and contravariance in generic type parameters (including IEnumerable
), which allows the compiler to implicitly convert statements like this.
When defining your own generic types, you can declare types as covariant or contravariant using the in
and out
keywords, respectively.
Upvotes: 1
Reputation: 65516
I believe that this is only available in .net 4
in earlier versions you can:
using System.Linq;
IEnumerable<IEntry> func()
{
return new List<Entry>().Cast<IEntry>();
}
Upvotes: 4