Null forgiving operator
Context: The null forgiving operator (!) suppresses nullable warnings when you are certain that an expression is not null.
#nullable enablestring? maybeNull = GetString();int length = maybeNull!.Length; // no warning, but riskyUse cases
Section titled “Use cases”- 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
Real-world usage example
Section titled “Real-world usage example”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.