C# Reference ยท Operators and Expressions
C# null-forgiving operator !
Reference for the C# null-forgiving (suppression) operator !: how it silences nullable warnings, what it does at run time, and safer alternatives.
The null-forgiving operator is a postfix ! placed after an expression. It tells the compiler's nullable analysis: "I know this reference is not null here, stop warning me." It has no effect at run time; it only changes what the compiler believes.
It is an escape hatch for cases the flow analysis cannot prove, such as fields set by a framework, values checked in another method, or test code. It does not check anything. If you are wrong, you get a NullReferenceException later, exactly as if nullable reference types were off.
string? input = Environment.GetEnvironmentVariable("HOME"); int n = input!.Length; // no warning, but a crash if input is null
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
expression!
| Part | Description |
|---|---|
expression! |
Same value and type as expression, but its null-state is "not null" for the analysis. |
Returns: the operand, unchanged. Its static type is the non-nullable form of the operand's type.
Errors: none from the operator itself. If the value is null at run time, the next dereference throws NullReferenceException. In a project without nullable annotations enabled the operator is allowed and does nothing.
Usage notes
- Compile-time only. The compiler emits no code for
!. It removes the nullable warning on that one expression. - Different from logical NOT. The prefix
!xnegates a bool; the postfixx!is the suppression. - Not the same as
?.or??. Those handle null at run time;!just hides the warning. - Common valid uses:
null!on a property that a framework initializes (dependency injection, serializers), a field assigned in a method called from the constructor, and test code that checksAssertresults the compiler cannot follow. - Better tools. Prefer the
requiredmodifier, constructors that set values,[MemberNotNull],[NotNullWhen(true)]and[NotNull]attributes,ArgumentNullException.ThrowIfNull, or pattern checks (is not null) over!. - Review them. Every
!is a promise that is easy to break during refactoring. Search for!.in code reviews and require a reason. - Generics.
default!is the usual way to return "no value" from a generic method whereTis not known to be nullable. - Enabling the analysis. Set
<Nullable>enable</Nullable>in the project or use#nullable enablein a file (the runner here has it enabled).