Voo
Voo

Reputation: 30245

Covariance and generic types

Why does the following code give a compile error for the generic case?

abstract class Test<TItem> where TItem : IFoo
{
    public IEnumerable<IFoo> Foos { get; set; }

    public void Assign()
    {
        Foos = GetSomeSpecificList(); // works as expected
        Foos = GetSomeGenericList(); // compile error?
    }

    protected abstract ICollection<TItem> GetSomeGenericList();

    protected abstract ICollection<Foo> GetSomeSpecificList();
}

interface IFoo
{
}

class Foo : IFoo
{
}

Am I missing something or isn't it given that every TItem must be an IFoo and therefore it's impossible for this construct to violate type safety?

Upvotes: 5

Views: 74

Answers (1)

user743382
user743382

Reputation:

You don't have a class constraint, therefore TItem could be a struct type implementing the IFoo interface. Covariance requires reference types. When you add the class constraint, it compiles without issues.

Upvotes: 7

Related Questions