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.
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:
#nullable disable (or an equivalent project-wide setting), which turns off both nullable annotations and nullable
warnings.#nullable disable warnings, which turns off only the warnings while nullable annotations (and flow-state tracking)
remain active.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:
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 !.
#nullable disable
string Method()
{
string s = null;
return s!.ToString(); // Noncompliant: nullable warnings are disabled, "!" suppresses nothing
}
#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
}