Skip to content

Null forgiving operator

Context: The null forgiving operator (!) suppresses nullable warnings when you are certain that an expression is not null.

#nullable enable
string? maybeNull = GetString();
int length = maybeNull!.Length; // no warning, but risky
  • When you know a value is not null despite the compiler’s analysis
  • For unit testing where you intentionally assign null
  • Interop with frameworks that use non‑nullable types but may return null

Dependency injection: When you register a service as non‑nullable but the DI container guarantees it, you can use ! after resolving.

var service = services.GetRequiredService<IMyService>()!;

Example: In ASP.NET Core, GetRequiredService throws if not found, so using ! is safe.