Oliver Zheng
Oliver Zheng

Reputation: 8199

Why can I not return List<Entry> when the return type is IEnumerable<IEntry>?

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

Answers (2)

Cameron
Cameron

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

Preet Sangha
Preet Sangha

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

Related Questions