JetBrains Rider 2022.2 Help

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

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.

JetBrains Rider 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.

public void Foo(IEnumerable<BaseType> list) { // Possible 'System.InvalidCastException' when casting from BaseType to DerivedType foreach (DerivedType item in list) { // do something } }

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

public void Foo(IEnumerable<BaseType> list) { foreach (var baseType in list) { var item = (DerivedType) baseType; // do something } }

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:

public void Foo(IEnumerable<BaseType> list) { foreach (DerivedType item in list.OfType<DerivedType>()) { // do something only with objects of DerivedType } }
Last modified: 08 March 2021