S8970 — Null-forgiving operators should not be used when nullable warnings are disabled

Language
C#
Type
Code smell
Severity
Minor
Tags
redundant

The null-forgiving operator (!) should only be used to suppress a nullable warning that the compiler would otherwise report. When nullable warnings are disabled at that point in the code, there is no warning to suppress, and the operator is redundant.

Why is this an issue?

The null-forgiving operator ! tells the compiler’s nullable analysis to suppress a warning it would otherwise emit about a possible null dereference, assignment, or return. It has no effect at runtime; it is purely an instruction to the compiler.

Nullable warnings can be disabled in two independent ways:

In either case, the compiler cannot report a nullable warning at that location, so ! has nothing to suppress. Removing it does not introduce a new warning, and keeping it does not prevent one.

Left in the code, the operator:

How to fix it

Remove the null-forgiving operator. If nullable warnings should apply at that location, enable them (e.g. with #nullable enable or #nullable enable warnings) instead of suppressing them with !.

Code examples

Noncompliant code example


#nullable disable

string Method()
{
    string s = null;
    return s!.ToString(); // Noncompliant: nullable warnings are disabled, "!" suppresses nothing
}

Compliant solution


#nullable disable

string Method()
{
    string s = null;
    return s.ToString();
}

The same applies when only warnings are disabled, even though annotations are still meaningful there:


#nullable enable

void Log(string? message)
{
#nullable disable warnings
    Console.WriteLine(message!); // Noncompliant: warnings are disabled here too
#nullable enable
}

#nullable enable

void Log(string? message)
{
#nullable disable warnings
    Console.WriteLine(message);
#nullable enable
}

Resources

Documentation

Related rules

↑ Back to top