
Why Nullable Reference Types Still Let Nulls Through at Runtime
- كاتب موثّق
- .NET 10
محتويات المقال
public record CreateOrder(string CustomerId, string Email);, nullable reference types enabled and zero warnings in the build. A partner integration sends a request without the email field. The JSON deserializer builds the record anyway, and a few calls later order.Email.ToLowerInvariant() throws NullReferenceException inside the notification service, on a line the compiler had declared safe. The 500 shows up in the partner's logs, not at the API boundary where the request could have been rejected with a clear 400.
The common misconception
<Nullable>enable</Nullable> is on, a variable declared as string can never hold null at runtime. Only string? can.
string, when you dereference a string? without checking it, and when a constructor leaves a non-nullable property unset. A codebase with zero nullable warnings really does have far fewer null bugs. And the syntax looks like int versus int?, where int truly can't be null. The difference is that int? is a separate runtime type, Nullable<int>. string? isn't.
What actually happens
The ? is an annotation, not a type
? is an annotation, not a typestring and string? are both System.String. The ? records your intent so the compiler's can track which expressions are not-null and which are maybe-null. No check is emitted when a value is assigned or passed in. A null travels freely until something dereferences it, and only then does it throw.
The analysis only sees code it compiles
Deserializers and mappers: they build objects through constructors and setters at runtime, so a JSON nullor a missing field becomes null in a non-nullable property without a single warning.Oblivious code: code compiled with nullable disabled, such as older libraries and generated files, is called nullable-oblivious. It can pass null to your stringparameter, and the compiler won't warn about that call.The : name!.Lengthand= null!tell the compiler to stop worrying. The docs call each one a place where the compiler can no longer protect you.Known gaps: new string[3]creates three null elements, anddefaultof a struct leaves its non-nullable reference fields null. Neither one produces a warning.
Warnings, not errors
#nullable disable regions or NoWarn, and that code stays unchecked until someone turns it back on. And the nullable attributes such as [NotNullWhen] and [MemberNotNull] don't change that. They give the analysis more information, but in the docs' words, they don't enable more checks on your implementation.
The partner request, before and after
using System.Text.Json;var json = """{"CustomerId":"c-42"}"""; // the partner forgot Emailvar order = JsonSerializer.Deserialize<CreateOrder>(json) ?? throw new JsonException("Empty body");// No warning: Email is a non-nullable string, but it holds nullConsole.WriteLine(order.Email.ToLowerInvariant()); // NullReferenceExceptionpublic record CreateOrder(string CustomerId, string Email);using System.Text.Json;var options = new JsonSerializerOptions{ RespectNullableAnnotations = true, // "Email": null throws RespectRequiredConstructorParameters = true, // a missing Email throws};var json = """{"CustomerId":"c-42"}""";try{ JsonSerializer.Deserialize<CreateOrder>(json, options);}catch (JsonException){ Console.WriteLine("400 Bad Request: Email is required"); // fails early}public record CreateOrder(string CustomerId, string Email);string is null. Since .NET 9, two opt-in options close that door: RespectNullableAnnotations rejects an explicit null for a non-nullable property or parameter, and RespectRequiredConstructorParameters rejects a missing constructor parameter. Microsoft recommends both for new applications. The bad request now fails at the edge, with a message that names the field, instead of deep inside a service.
public sealed class EmailSender{ public void Send(string to, string body) { // Oblivious callers, or a stray !, can still pass null here ArgumentException.ThrowIfNullOrWhiteSpace(to); ArgumentNullException.ThrowIfNull(body); Console.WriteLine($"Sending {body.Length} chars to {to}"); }}Myth vs reality
string can't hold null once nullable is enabled | string and string? are the same runtime type; nothing checks at runtime |
! operator checks for null | |
How to apply it in your project
Turn nullable warnings into errors Add <WarningsAsErrors>nullable</WarningsAsErrors>so the compile-time promise stays complete as the code changes.Validate every boundary Enable RespectNullableAnnotationsandRespectRequiredConstructorParameterson your JSON options, mark mandatory propertiesrequired, and validate request models before they reach business logic.Guard public entry points In libraries and shared services, call ArgumentNullException.ThrowIfNullorArgumentException.ThrowIfNullOrWhiteSpaceon parameters that callers outside your nullable context can reach.Audit every ! and null! Search for the null-forgiving operator. Replace each one with a real check, proper initialization or a requiredmember, and keep only the ones you can justify in a comment.
Key takeaways
Nullable reference types are compile-time only: stringandstring?are the same type at runtime.The analysis can't see nulls from deserializers, oblivious libraries, !, new arrays or default structs.Since .NET 9, System.Text.Json can enforce annotations, but only when you opt in, and with limits. Validate data at boundaries and guard public APIs with ThrowIfNull; treat nullable warnings as errors.Keep the annotations: they prevent most null bugs, as long as you know which doors they don't lock.
📚 المصادر
Nullable reference types (C#) — Microsoft Learn Nullable migration strategies (C#) — Microsoft Learn Attributes for nullable static analysis (C# reference) — Microsoft Learn Respect nullable annotations (System.Text.Json) — Microsoft Learn Require properties for deserialization (System.Text.Json) — Microsoft Learn
التعليقات (0)