The following code gives you a compiler error, as you’d expect:
List<Banana> aBunchOfBananas = new List<Banana>();
Banana justOneBanana = (Banana)aBunchOfBananas;
However, when using IEnumerable<Banana>, you merely get a runtime error.
IEnumerable<Banana> aBunchOfBananas = new List<Banana>();
Banana justOneBanana = (Banana)aBunchOfBananas;
Why does the C# compiler allow this?
I would suppose it’s because
IEnumerable<T>is an interface where some implementation could have an explicit cast toBanana– no matter how silly that would be.On the other hand, the compiler knows that
List<T>can’t be explicitly cast to aBanana.Nice choice of examples, by the way!
Adding an example to clarify. Maybe we’d have some “enumerable” that should always contain at most a single
Banana:Then you could actually do this:
As it’s the same as writing the following, which the compiler is perfectly happy with: