skip to content

In C#, what does the null-forgiving operator ! do at compile time and at run time, and when does using it become a problem?

level: middleimportance: must knowfreq 60%

answer

  1. postfix, not logical negation
  2. suppresses, never checks
  3. null! initializers
  4. moves the crash elsewhere

basics

~20 s

Postfix ! tells the compiler an expression is not null, suppressing nullable warnings for that expression. It emits no code and no check: x! evaluates to x, so a wrong ! simply moves the NullReferenceException to a later line.

solid answer

~40 s

The postfix `!` is the **null-forgiving** (null-suppression) operator. In an enabled annotation context it changes the null-state of the expression it follows to not-null and suppresses every nullable warning for that expression; at run time `x!` is just `x`, with no check. It suppresses only that one expression: `_ = a!;` leaves `a` maybe-null for the next line, although `a!.Length` makes `a` not-null afterwards, as any dereference does. Legitimate uses are narrow: a test that passes `null` on purpose to check a guard, or an invariant the compiler cannot see. It becomes a problem when it is used to silence warnings: `= null!` initializers that never get replaced, `Find(id)!` on a lookup that can miss, `!` sprinkled during migration. Each one is a place the analysis stops protecting you.

code

csharp · 15 lines
csharp
var draft = new Ticket();                  // no CS8618: '= null!' silenced it
Console.WriteLine(draft.Subject is null);  // True: ! changed nothing at run time

Ticket? missing = TicketStore.Find(404);
try { Console.WriteLine(missing!.Subject); } // no warning, no check
catch (NullReferenceException) { Console.WriteLine("NullReferenceException"); }

object code = 5;
Console.WriteLine(code !is string);          // False: parsed as (code!) is string

class Ticket { public string Subject { get; set; } = null!; }
static class TicketStore
{
    public static Ticket? Find(int id) => id == 1 ? new Ticket { Subject = "Login" } : null;
}

go deeper

for a junior

Recall that the postfix ! silences nullable warnings and does nothing at run time, unlike the prefix ! for logical negation.

for a middle

Explain that it changes the null-state of one expression only, why a later dereference behaves differently, and the legitimate test and invariant uses.

for a senior

Spot the abuses in review: forgiven lookups that can miss, null! initializers nothing replaces, and ! used where an annotated helper would fix every call site.

for a principal

Decide the team rule: whether ! needs a justifying comment, how null! debt from a migration is tracked down, and when attributes replace suppression.

## What the operator is C# has two operators spelled `!`. The **prefix** `!` is logical negation (`!done`). The **postfix** `!`, written after an expression, is the **null-forgiving** or **null-suppression** operator (`customer!`). It arrived with nullable reference types in C# 8. In an enabled annotation context it does two things, both at compile time: - It sets the **null-state** of that expression to not-null. - It suppresses all nullable warnings for that expression: no CS8602 on `x!.Length`, no CS8625 on `Take(null!)`, no CS8600 on `string s = maybe!;`. At run time it does **nothing**. The documentation states it directly: `x!` evaluates to the result of `x`. No IL is emitted for it, no check is inserted, and no exception is thrown by the operator itself. In a disabled annotation context it is still allowed and has no effect. ## Not to be confused with - `x?.Member` is null-conditional access: it checks at run time and yields null instead of throwing. - `x ?? fallback` supplies a value at run time when `x` is null. - `!flag` is prefix logical negation on a `bool`. - `x!` has no run-time behavior at all; only the compiler's view of `x` changes. The first two are covered with coalescing and conditional access; they are the operators that actually do something about a null when the code runs. ## Scope: one expression The operator affects the expression it is attached to, not the variable for the rest of the method: | Code | What the compiler concludes afterwards | |---|---| | `_ = a!;` then `a.Length` | `a` is still maybe-null, so CS8602 on `a.Length` | | `a!.Length` then `a.Length` | `a` is not-null, because any dereference marks it not-null | | `string s = a!;` then `s.Length` | `s` is not-null; `a` itself is unchanged | The middle row is not special to `!`: after any dereference the compiler assumes the variable was not null, since execution got past it. A precedence trap shows the operator is real syntax: `if (o !is string)` does **not** mean "o is not a string". It parses as `(o!) is string`, so the null-forgiving operator does nothing and the test is the positive one. The IDE analyzer rule IDE0080 flags this as an unnecessary suppression operator; the intended spelling is `o is not string`. ## Legitimate uses 1. **Tests of argument guards.** A unit test that checks a constructor throws on null has to pass `null` to a non-nullable parameter; `new Customer(null!)` states that the null is intentional. 2. **Invariants the compiler cannot see**, when you cannot annotate the API that establishes them, for example a value guaranteed by an earlier call in another method. 3. **Late initialization during a migration**, such as `public string Subject { get; set; } = null!;` on a type a framework populates after construction. It silences CS8618, and it should be temporary: the end state of a migration removes `null!` and `default!` initializers in favour of real initialization, `required` members or a nullable type. ## When it becomes a problem The operator turns off the one tool that was pointing at the bug. Typical abuses: - `var customer = repository.Find(id)!;` where `Find` returns `Customer?` because a miss is normal. The warning was correct; the fix is a check, a different method that throws on a miss, or a nullable variable. - Adding `!` to every CS8602 during a migration to "get to zero warnings". The warning count drops and the null exceptions stay. - `= null!` on a property that nothing ever sets, which leaves a non-nullable property null at run time with no warning anywhere. - Using `!` where a nullability attribute on the API would let the compiler reach the right conclusion at every call site at once. When the assumption behind a `!` is wrong, the `NullReferenceException` happens wherever the value is first dereferenced, which may be far from the `!` that hid the warning. That is why code review treats each `!` as a claim that needs a reason, and why the documentation recommends a null check, restructuring, or an annotated API before reaching for it. ## A short decision list - Can the value really be null here? Then check it, or declare it nullable. - Is a helper proving non-null? Then annotate the helper rather than every caller. - Is the value set by a framework after construction? Then prefer `required` members or constructor parameters, and keep `null!` as a dated migration step. - Is it a test of a null guard? Then `null!` is the honest spelling.

  • Does x! insert a run-time check, like ArgumentNullException.ThrowIfNull?
    No. `x!` evaluates to `x` and emits no code; it only changes what the compiler believes. If you need a run-time guarantee you write the check yourself, and a throw helper is what does that; the lesson on throwing and catching covers those helpers.
  • Why is `public string Name { get; set; } = null!;` a common migration pattern, and why remove it later?
    It silences CS8618 on types that something fills after construction, so a migration can reach zero warnings quickly. It also leaves the property null until that happens, with no warning anywhere, so the finished migration replaces it with a constructor parameter, a `required` member or a nullable type.
  • What does `if (o !is string)` mean in C#?
    It parses as `(o!) is string`: a null-forgiving operator followed by a positive type test. The branch runs when `o` is a string, the opposite of what the author meant. IDE0080 flags the useless `!`; write `o is not string` instead.

Ticking a checklist item yourself: the auditor stops flagging that line, but whatever the item was checking is exactly as true or false as before.

  • x! throws if x is null, like a non-null assertion.
  • One a! makes a non-null for the rest of the method.
  • null! on a property gives it a non-null value at run time.
  • Adding ! to every warning is a safe way to finish a migration.
  • o !is string tests that o is not a string.