Is is possible to make the following compile without:
- Making
IFooCollectiongeneric - Explicitly implementing
IFooCollection.ItemsonFooCollectionand performing an explicit cast.
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’m happy enough with the second solution (implementing the interface explicitly) but would like to understand why I need to cast T as IFoo when we have a generic constraint specifying that T must implement IFoo.
The reason is the following:
IFooCollection.Itemscan contain any class that implementsIFoo. So it can containFooA,FooB,FooCat the same time.FooCollection<FooA>.Itemson the other hand can only contain elements of typeFooA. Trying to castFooBorFooCtoFooAwould yield anInvalidCastExceptionalthough all implementIFoo.