Use coalesce expression (IDE0029 and IDE0030)
This article describes two related rules, IDE0029
and IDE0030
.
Property | Value |
---|---|
Rule ID | IDE0029 |
Title | Use coalesce expression (non-nullable types) |
Category | Style |
Subcategory | Language rules (null-checking preferences) |
Applicable languages | C# and Visual Basic |
Options | dotnet_style_coalesce_expression |
Property | Value |
---|---|
Rule ID | IDE0030 |
Title | Use coalesce expression (nullable types) |
Category | Style |
Subcategory | Language rules (null-checking preferences) |
Applicable languages | C# and Visual Basic |
Options | dotnet_style_coalesce_expression |
Overview
These style rules concern the use of null-coalescing expressions, for example, x ?? y
, versus ternary conditional expressions with null
checks, for example, x != null ? x : y
. The two related rule IDs differ with respect to the nullability of the expressions:
IDE0029
: Used when non-nullable expressions are involved. For example, this rule could recommendx ?? y
instead ofx != null ? x : y
whenx
andy
are non-nullable reference types.IDE0030
: Used when nullable expressions are involved. For example, this rule could recommendx ?? y
instead ofx != null ? x : y
whenx
andy
are nullable value types or nullable reference types.
Options
Set the value of the associated option to specify whether null-coalescing expressions or ternary operator checking is preferred. The rule enforces whichever option you choose.
For more information about configuring options, see Option format.
dotnet_style_coalesce_expression
Property | Value | Description |
---|---|---|
Option name | dotnet_style_coalesce_expression | |
Option values | true |
Prefer null coalescing expressions to ternary operator checking |
false |
Prefer ternary operator checking to null coalescing expressions | |
Default option value | true |
// dotnet_style_coalesce_expression = true
var v = x ?? y;
// dotnet_style_coalesce_expression = false
var v = x != null ? x : y; // or
var v = x == null ? y : x;
' dotnet_style_coalesce_expression = true
Dim v = If(x, y)
' dotnet_style_coalesce_expression = false
Dim v = If(x Is Nothing, y, x) ' or
Dim v = If(x IsNot Nothing, x, y)
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 IDE0029 // Or IDE0030
// The code that's violating the rule is on this line.
#pragma warning restore IDE0029 // Or IDE0030
To disable the rule for a file, folder, or project, set its severity to none
in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.IDE0029.severity = none
dotnet_diagnostic.IDE0030.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.
See also
Feedback
Submit and view feedback for