Is is possible to make the following compile without:
IFooCollection
genericIFooCollection.Items
on FooCollection
and 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.Items
can contain any class that implements IFoo
. So it can contain FooA
, FooB
, FooC
at the same time.
FooCollection<FooA>.Items
on the other hand can only contain elements of type FooA
. Trying to cast FooB
or FooC
to FooA
would yield an InvalidCastException
although all implement IFoo
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With