ReSharper
 
Get ReSharper
Get your hands on the new features ahead of the release by joining the Early Access Program for ReSharper 2025.1! Learn more

Code inspection: Possible 'System.InvalidCastException' in foreach loop

Last modified: 11 February 2024

By design, foreach allows a hidden cast to a derived type. On the one hand, this makes it easy to use, but on the other hand, this can lead to a runtime exception.

ReSharper wants you to be on the safe side and therefore notifies of possible System.InvalidCastException if it detects an unsafe cast like the one in the example below.

The quick-fix that ReSharper suggests here helps you make the cast explicit. It is still not safe, but it is not hidden anymore:

If the cast is intended, it is recommended to replace the explicit type reference with var.

If your collection implements IEnumerable and you use members of DerivedType that are not present in the BaseType, you may want to filter your collection before iterating. Note that this will change the semantics: