Why a casting exception is thrown at runtime instead of handled at compile time for variance mis-match #8664
Labels
Area-Language Design
Feature Request
Resolution-Won't Fix
A real bug, but Triage feels that the issue is not impactful enough to spend time on.
I'm not sure if this is a bug, or by design, as it's existed for a while (forever?) in C#. If I have a method called
GetFoo()
that returns anIEnumerable<IFoo>
, then the following code will fail despiteFooBar
implementingIFoo
This gives the correct compiler error of
However, if I use the
GetFoo()
method in aforeach
loop, where each element is of TypeFooBar
, there are no compiler errors. Instead, a runtime exception is thrown.The compiler can tell that the Type specified on the left side, can not be safely cast to the
IBar
returned on the right side of the expression. Shouldn't it have a compiler error to state this?I can see this being a nice feature, if the developer can 100% with certainty know that
GetFoo()
will return every element asFooBar
; that feels unsafe to me in a language that has strong roots in Type safety.I have an example that reproduces this if anyone wants to clone and run it.
The text was updated successfully, but these errors were encountered: