Use pattern matching to avoid 'as' followed by a 'null' check (IDE0019)
Property | Value |
---|---|
Rule ID | IDE0019 |
Title | Use pattern matching to avoid as followed by a null check |
Category | Style |
Subcategory | Language rules (pattern matching preferences) |
Applicable languages | C# |
Options | csharp_style_pattern_matching_over_as_with_null_check |
Overview
This style rule concerns the use of C# pattern matching over an as
expression followed by a null
check. This rule is similar to IDE0260, which flags the use of an as
expression followed by a member read through the null-conditional operator.
Options
The associated option for this rule specifies whether to prefer pattern match or an as
expression with null checks to determine if something is of a particular type.
For more information about configuring options, see Option format.
csharp_style_pattern_matching_over_as_with_null_check
This option also configures rule IDE0260.
Property | Value | Description |
---|---|---|
Option name | csharp_style_pattern_matching_over_as_with_null_check | |
Option values | true |
Prefer pattern matching to determine if something is of a particular type |
false |
Prefer as expressions with null checks to determine if something is of a particular type |
|
Default option value | true |
// csharp_style_pattern_matching_over_as_with_null_check = true
if (o is string s) {...}
// csharp_style_pattern_matching_over_as_with_null_check = false
var s = o as string;
if (s != null) {...}
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 IDE0019
// The code that's violating the rule is on this line.
#pragma warning restore IDE0019
To disable the rule for a file, folder, or project, set its severity to none
in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.IDE0019.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.