All rules
IDE0220Language rules (expression-level preferences)

Add explicit cast

Add explicit cast

Microsoft docs

Description

This rule flags the absence of an explicit cast in a foreach loop when the compiler would add a hidden cast. For generic, or strongly typed, collections, forcing an explicit cast when the compiler would add a hidden cast can uncover the use of an incorrect type in the foreach statement.

Example

// Code with violations.
var list = new List<object>();
foreach (string item in list) { }

// Fixed code.
var list = new List<object>();
foreach (string item in list.Cast<string>())

Configurable options

Vote for the value each option should take in the generated .editorconfig.

dotnet_style_prefer_foreach_explicit_cast_in_source
default: when_strongly_typed
Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0