All rules
IDE0030Language rules (expression-level preferences)

Null check can be simplified (if null check)

Null check can be simplified (if null check)

Microsoft docs

Description

Rules IDE0029 and IDE0030 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 rules differ with respect to the nullability of the expressions:

  • IDE0029: Used when non-nullable expressions are involved. For example, this rule could recommend x ?? y instead of x != null ? x : y when x and y are non-nullable reference types.
  • IDE0030: Used when nullable expressions are involved. For example, this rule could recommend x ?? y instead of x != null ? x : y when x and y are nullable value types or nullable reference types.

Rule IDE0270 flags the use of a null check (== null or is null) instead of the null-coalescing operator (??).

Example

// Code with violation.
var v = x != null ? x : y; // or
var v = x == null ? y : x;

// Fixed code.
var v = x ?? y;

// Code with violation.
class C
{
    void M()
    {
        var item = FindItem() as C;
        if (item == null)
            throw new System.InvalidOperationException();
    }

    object? FindItem() => null;
}

// Fixed code (dotnet_style_coalesce_expression = true).
class C
{
    void M()
    {
        var item = FindItem() as C ?? throw new System.InvalidOperationException();
    }

    object? FindItem() => null;
}

Configurable options

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

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