đź”§ C#: Fix a Nullable Warning Silenced by an Unsafe Cast
Nullable reference type analysis is a compile-time, flow-based warning system, and an explicit cast like (string)maybeNullValue is one of the operations the compiler treats as an assertion that you already know better — it suppresses the nullable warning at that line without inserting any actual runtime null check. Unlike the null-forgiving ! operator, which is specifically designed to be visible and greppable as an intentional override, a plain cast looks like an ordinary, unremarkable cast to a reviewer, hiding exactly the risk it introduces.
🔎 The Problem
#nullable enable string? maybeName = LookupName(id); // Looks like a routine cast; actually suppresses the nullable // warning with zero runtime verification that maybeName isn't null: string name = (string)maybeName; Console.WriteLine(name.Length); // NullReferenceException at runtime if LookupName returned null - // the compiler gave no warning here at all
âś… Fix: Make Any Deliberate Override Visible and Searchable
- Prefer the null-forgiving operator
!over a cast when you’ve manually verified a value can’t be null here — it communicates the same intent to the compiler while staying immediately visible and easy to find with a project-wide search. - Where the value’s nullability genuinely needs to be checked rather than merely asserted, use
ArgumentNullException.ThrowIfNullor an explicitif (x is null)pattern so a real null actually throws a clear exception instead of flowing silently into later code. - During code review, treat an explicit reference-type cast the same way you’d treat a null-forgiving
!— as a claim that deserves a one-line justification, not as an unremarkable, self-evidently safe operation.
🚨 Why This Is Dangerous
- A cast that silences a nullable warning doesn’t just suppress it for the current code — it keeps suppressing it after later edits change what’s being assigned, so a value that was genuinely non-null when the cast was written can become nullable again without the compiler ever re-flagging that line.
The null-forgiving operator says ‘I checked this’ out loud; a cast says the same thing in a whisper a reviewer has no reason to listen for.

