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:
- Fully, with
#nullable disable(or an equivalent project-wide setting), which turns off both nullable annotations and nullable warnings. - Partially, with
#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:
- Adds visual noise without changing behavior.
- Misleads readers into believing nullable warnings are active at that location, when they are not.
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
- Microsoft Learn - ! (null-forgiving) operator
- Microsoft Learn - Nullable reference types
- Microsoft Learn - #nullable directive
Related rules
- {rule:csharpsquid:S8969} - Null-forgiving operators should not be redundant