An IEnumerable<B>
cannot contain objects of type A
because and A
is not a B
.
I can write this code,
IEnumerable<B> dodgy = (new[] { new A() }).Cast<B>();
It will compile, despite being obviously wrong. The compiler assumes I know what I'm doing. Remember that no item in the IEnumerable
sequence has yet been evaluated.
When I write code that evaluates a member of dodgy
I get exception because an A
is not a B
and does not support casting to B
.
I can write
IEnumerable<A> fine = new[] { new B() };
no cast is required and everything works fine because a B
is an A
.
If I do,
var hungrilyDodgy = (new[] { new A() }).Cast<B>().ToList();
the Tolist()
will force enumeration and evaluation of the IEnumerable
, therefore the exception will be thrown much sooner.