Latest on twitter:

Fooling the c# compiler

Summary: Don’t cast to interfaces unless you really have to. Use var in a foreach loop.

In my version of Visual Studio the code below will compile without a warning or error. However, it will throw a runtime exception.

foreach ( IDictionary x in new List<IList>() ) {
}

To compare: the as-you-type-checker is smart enough to catch the sillyness of

foreach ( IDictionary x in new List<int>() ) {
}

and the compile-time-checker is smart enough to catch:

foreach ( String x in new List<IList>() ) {
}

It seems that in a foreach loop the code simply performs a cast to the given type. What’s worse: it seems that the compiler will let you cast to an Interface without checking if that is even remotely possible.

So once you cast to an interface, you loose type safety. This isn’t that much of a problem since seeing (someType) in your code should trigger warning bells anyway1 but since the foreach loop contains an implicit cast, you should always use the var keyword to avoid runtime errors.

For example if you iterate over a variable of typeIList, and then later you change the variable to be of type IEnumerable (happily expecting the compiler to flag all places that you need to change) you will have introduced a guaranteed runtime error.


  1. Don’t get me wrong: it’s totally fine to use a cast when necessary, but it is a sign that you are stepping away from the safety of static typing. Often the code will benefit from an approach that makes the cast unnecessary