Covariance and general types

Why does the following code give a compilation error for the general 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 didn’t get that each TItem should be IFoo, and therefore it is not possible for this construct to violate type safety?

+5
source share
1 answer

You do not have a class constraint, so TItem can be a struct type that implements the IFoo interface. Covariance requires reference types. When you add a class constraint, it compiles without problems.

+7
source

All Articles