Use pattern matching to avoid 'is' check followed by a cast (IDE0020 and IDE0038)
This article describes two related rules, IDE0020
and IDE0038
.
Property | Value |
---|---|
Rule ID | IDE0020 |
Title | Use pattern matching to avoid is check followed by a cast (with variable) |
Category | Style |
Subcategory | Language rules (pattern matching preferences) |
Applicable languages | C# |
Options | csharp_style_pattern_matching_over_is_with_cast_check |
Property | Value |
---|---|
Rule ID | IDE0038 |
Title | Use pattern matching to avoid is check followed by a cast (without variable) |
Category | Style |
Subcategory | Language rules (pattern matching preferences) |
Applicable languages | C# |
Options | csharp_style_pattern_matching_over_is_with_cast_check |
Overview
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.
Options
Set the value of the associated option for this rule to specify whether pattern matching or is
check followed by a type cast is preferred.
For more information about configuring options, see Option format.
csharp_style_pattern_matching_over_is_with_cast_check
Property | Value | Description |
---|---|---|
Option name | csharp_style_pattern_matching_over_is_with_cast_check | |
Option values | true |
Prefer pattern matching instead of is expressions with type casts. |
false |
Disables the rule. | |
Default option value | true |
// 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; ... }
Suppress a warning
If you want to suppress only a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.
#pragma warning disable IDE0020 // Or IDE0038
// The code that's violating the rule is on this line.
#pragma warning restore IDE0020 // Or IDE0038
To disable the rule for a file, folder, or project, set its severity to none
in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.IDE0020.severity = none
dotnet_diagnostic.IDE0038.severity = none
To disable all of the code-style rules, set the severity for the category Style
to none
in the configuration file.
[*.{cs,vb}]
dotnet_analyzer_diagnostic.category-Style.severity = none
For more information, see How to suppress code analysis warnings.