الانتقال إلى المحتوى
.NETC#· 6 دقائق للقراءة

Why Nullable Reference Types Still Let Nulls Through at Runtime

string versus string? is a compile-time promise, not a runtime check. Where nulls still get in, and how to close the doors.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • .NET 10
محتويات المقال

An order API has 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

The belief: once <Nullable>enable</Nullable> is on, a variable declared as string can never hold null at runtime. Only string? can.

It's an understandable belief, because the feature is good at its job. The compiler warns when you assign null to a 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

Microsoft's docs are explicit: the runtime behavior of your program is unchanged, and nullable reference types are entirely a compile-time feature. string 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

The compiler reasons about your source code. Anything that creates objects at runtime, or was compiled without your annotations, is outside its view. That's where nulls get in:

  • Deserializers and mappers: they build objects through constructors and setters at runtime, so a JSON null or 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 string parameter, and the compiler won't warn about that call.
  • The : name!.Length and = 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, and default of a struct leaves its non-nullable reference fields null. Neither one produces a warning.

Warnings, not errors

Nullable diagnostics are warnings, so a project full of them still builds and ships. During a migration, teams also switch them off with #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

The first tab trusts the annotations. The second asks System.Text.Json to enforce them at the boundary:

C# Program.cs
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);

By default, System.Text.Json treats every constructor parameter as optional and fills a missing one with its default value, which for a 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.

For code you don't control calling into yours, guard public entry points with real runtime checks:

C# EmailSender.cs
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

MythReality
A string can't hold null once nullable is enabledstring and string? are the same runtime type; nothing checks at runtime
Zero warnings means no nullsIt means no nulls the analysis can see in code it compiled
Deserializers respect the annotationsOnly with opt-in options, and even then with blind spots
The ! operator checks for nullIt only silences a warning; no code runs
Nullable attributes add runtime checksThey inform the analysis; your implementation isn't checked

How to apply it in your project

  1. Turn nullable warnings into errorsAdd <WarningsAsErrors>nullable</WarningsAsErrors> so the compile-time promise stays complete as the code changes.
  2. Validate every boundaryEnable RespectNullableAnnotations and RespectRequiredConstructorParameters on your JSON options, mark mandatory properties required, and validate request models before they reach business logic.
  3. Guard public entry pointsIn libraries and shared services, call ArgumentNullException.ThrowIfNull or ArgumentException.ThrowIfNullOrWhiteSpace on parameters that callers outside your nullable context can reach.
  4. Audit every ! and null!Search for the null-forgiving operator. Replace each one with a real check, proper initialization or a required member, and keep only the ones you can justify in a comment.

Key takeaways

  • Nullable reference types are compile-time only: string and string? 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.

📚 المصادر

  1. Nullable reference types (C#) — Microsoft Learn
  2. Nullable migration strategies (C#) — Microsoft Learn
  3. Attributes for nullable static analysis (C# reference) — Microsoft Learn
  4. Respect nullable annotations (System.Text.Json) — Microsoft Learn
  5. Require properties for deserialization (System.Text.Json) — Microsoft Learn

التعليقات (0)