Is it possible to do the following compilation without:
IFooCollection
IFooCollection.Items
FooCollection
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>.
T
IFoo
The reason is as follows:
IFooCollection.Itemscan contain any class that implements IFoo. Thus, it may contain FooA, FooB, FooCat the same time.
FooA
FooB
FooC
FooCollection<FooA>.Items, , FooA. FooB FooC FooA InvalidCastException, IFoo.
FooCollection<FooA>.Items
InvalidCastException