Casting a generic type to an interface type restriction

Is it possible to do the following compilation without:

  • Creating IFooCollectiongeneric
  • Explicitly implements IFooCollection.Itemson FooCollectionand perform an explicit conversion.

public interface IFoo
{

}

public interface IFooCollection
{
    IEnumerable<IFoo> Items { get; }
}

public class FooCollection<T> : IFooCollection where T : IFoo
{
    public IEnumerable<T> Items { get; set; }
}

I am quite satisfied with the second solution (which explicitly implements the interface), but I would like to understand why I need to use Thow IFoo, when we have a general restriction indicating what Tshould implement IFoo>.

+5
source share
1 answer

The reason is as follows:

IFooCollection.Itemscan contain any class that implements IFoo. Thus, it may contain FooA, FooB, FooCat the same time.

FooCollection<FooA>.Items, , FooA. FooB FooC FooA InvalidCastException, IFoo.

+9

All Articles