All rules
IDE0020Language rules (pattern matching preferences)

Use pattern matching to avoid is check followed by a cast (without variable)

Use pattern matching to avoid is check followed by a cast (without variable)

Microsoft docs

Description

This style rule concerns the use of C# pattern matching, for example, o is int i, over an is check followed by a cast, for example, if (o is int) { ... (int)o ... }. Enable either IDE0020 or IDE0038 based on whether or not the cast expression should be saved into a separate local variable:

  • IDE0020: Cast expression _is_ saved into a local variable. For example, if (o is int) { var i = (int)o; } saves the result of (int)o in a local variable.
  • IDE0038: Cast expression _is not_ saved into a local variable. For example, if (o is int) { if ((int)o == 1) { ... } } does not save the result of (int)o into a local variable.

Example

// csharp_style_pattern_matching_over_is_with_cast_check = true
if (o is int i) {...}

// csharp_style_pattern_matching_over_is_with_cast_check = false
if (o is int) {var i = (int)o; ... }

Configurable options

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

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