A C# service built with <Nullable>enable</Nullable> and no nullable warnings throws NullReferenceException on a non-nullable string property; how can null get there?
answer
- the analysis has edges
- code it never compiled
- arrays and default structs
- serializers and reflection skip it
basics
~20 sNon-nullable is a compile-time promise with no run-time check. Null still arrives from code the analysis never sees: deserializers and reflection, new arrays and default structs, callers or libraries compiled with nullable disabled, and ! or null! suppressions.
solid answer
~40 sNullable reference types only produce warnings in code compiled with the context enabled; nothing is enforced at run time. So a clean build still admits null through several doors: **System.Text.Json** and other reflection-based code set properties without the compiler, so `{"Email": null}` lands in a `string Email`; `new string[3]` and `default(SomeStruct)` hold nulls the compiler does not warn about; a **nullable-oblivious** caller (a `#nullable disable` file or an older library) can pass null to your `string` parameter, and an oblivious method's return is trusted as not-null; and `!` or `= null!` initializers that hide real nulls. The fixes sit at the boundaries: guard public entry points, validate deserialized objects, turn on `JsonSerializerOptions.RespectNullableAnnotations` (.NET 9 and later), and remove leftover `null!`.
code
csharp · 18 lines#:property PublishAot=false
using System.Text.Json;
var customer = JsonSerializer.Deserialize<Customer>("""{"Id":7,"Email":null}""")!;
var emails = new string[2]; // elements start null, no warning
var contact = default(Contact); // struct fields start null, no warning
string fromLegacy = Legacy.Find(7); // oblivious API, trusted as not-null
Console.WriteLine(customer.Email is null);
Console.WriteLine(emails[0] is null);
Console.WriteLine(contact.Phone is null);
Console.WriteLine(fromLegacy is null);
class Customer { public int Id { get; set; } public string Email { get; set; } = ""; }
struct Contact { public string Phone; public Contact(string phone) => Phone = phone; }
#nullable disable
static class Legacy { public static string Find(int id) => null; }
#nullable restorego deeper
Recall that non-nullable is checked only by the compiler, so null can still reach a string property at run time.
List the main sources: deserializers and reflection, arrays and default structs, nullable-disabled callers, and null-forgiving suppressions.
Trace an incident to its writer, distinguish explicit JSON null from an absent field, and put guards and validation at the boundaries rather than trusting annotations.
Decide where the team enforces nullability at run time: which entry points validate, whether serializers run with nullable annotations respected, and how null! debt is removed.
## Why a clean build is not a guarantee With `<Nullable>enable</Nullable>`, a non-nullable `string` is a promise the compiler checks **in the code it compiles with that context**. The compiler adds no null checks to the IL, and the runtime knows nothing about the annotation: `string` and `string?` are both `System.String`. Every path that writes a reference without going through nullable-aware C# can therefore write null into a member declared non-nullable, and the first sign is a `NullReferenceException`, often far from where the null came in. ## The doors null comes through | Source | Why no warning appears | |---|---| | Deserializers (System.Text.Json and others) | They create the object and set properties by reflection or generated code at run time; `{"Email": null}` assigns null to `string Email` by default | | Reflection, `Activator.CreateInstance`, object mappers | Same: the assignment is not C# the compiler analyzed | | `new string[n]` | Array elements start as null and the compiler does not warn | | `default(T)` of a struct, an array of structs | Reference fields inside start null; `default` of a struct is not flagged | | Callers compiled with nullable disabled | Their code is oblivious, so `Send(null)` raises no warning on their side | | Oblivious APIs you call | A `string` return from code compiled with nullable disabled is treated as not-null | | `!` and `= null!` | Each one tells the compiler to stop checking | | Member paths after a method call | A narrowed `order.Note` is not reset when a call sets it back to null | Four of these rows are in the snippet below, which compiles on the SDK 10.0.401 with no nullable warnings and prints `True` four times. ## Diagnosing the incident 1. **Find who wrote the null.** The stack trace shows where it was read; the writer is usually a deserializer, a mapper, a default-constructed struct or an oblivious caller. Look for `= null!` on that member first. 2. **Check the boundary.** If the object came from JSON, the payload either had an explicit `null` or omitted the field. These behave differently (see below). 3. **Check the callers.** A library with nullable enabled is still called by projects that have it disabled, and nothing on their side warns. 4. **Check suppressions.** Search for `!` on lookups of this property's owner; a forgiven `Find(id)!` that can miss is a common origin. ## Fixes that hold at run time Because the compiler cannot enforce anything at run time, the fixes put real checks where untrusted data enters: - **Guard public entry points.** A public method whose parameter is `string` still needs a run-time check if callers can be oblivious; the throw helpers for that are covered in the lesson on throwing and catching. - **Validate deserialized objects** before they reach domain code, or make the serializer enforce the annotations. Since .NET 9, `JsonSerializerOptions.RespectNullableAnnotations = true` makes System.Text.Json throw `JsonException` when JSON assigns an explicit `null` to a non-nullable property, field or constructor parameter (non-generic members only; collection elements and the top-level type are not checked), and .NET 10's `JsonSerializerOptions.Strict` preset turns it on. It does **not** reject a property that is simply absent: required-ness and nullability are separate in C#, so a missing field leaves the member at whatever the constructor or initializer set. - **Remove `null!` initializers** that were added to silence CS8618, replacing them with constructor parameters, `required` members (C# 11) or honest `string?` declarations. - **Initialize arrays** fully, for example with a collection expression, and avoid exposing structs whose `default` value breaks their own annotations. ## Where each fix belongs - **API boundary**, the public methods of a library: run-time guards, because oblivious callers exist. - **Wire boundary**, JSON bodies, queue messages and files: validation after deserialization, or serializer options that respect annotations. - **Persistence boundary**: data-access code also materializes objects by reflection or generated code; how a particular data-access library reads annotations belongs to that library's own material. - **Inside compiled code**: trust the annotations, and keep `!` rare enough that each one gets reviewed. ## What to say about the design The feature is deliberately a static analysis, not a type-system guarantee enforced by the runtime: that keeps existing binaries compatible and lets a codebase adopt it gradually. The trade-off is that the guarantee ends wherever code the compiler did not analyze begins. A senior answer names those edges and puts validation exactly there, instead of trusting the annotation alone or abandoning it.
- Your library has nullable enabled; do its public methods still need null checks on string parameters?Yes, if anyone outside your compilation calls them. A caller compiled with nullable disabled gets no warning for passing null, and neither does reflection. The annotation documents the contract; a run-time guard on public entry points enforces it.
- Does RespectNullableAnnotations make System.Text.Json reject a missing non-nullable property?No. It throws `JsonException` only when the JSON contains an explicit `null` for a non-nullable member. An absent property is a required-ness question, which System.Text.Json treats separately, so the member keeps whatever its constructor or initializer set.
- With nullable enabled, the runtime rejects null for non-nullable members.
- A clean nullable build means NullReferenceException is impossible.
- System.Text.Json refuses null for non-nullable properties by default.
- new string[3] produces a nullable warning because the elements are null.
- Public methods need no guards once the library enables nullable.
Assumes .NET 10; System.Text.Json's RespectNullableAnnotations exists since .NET 9, is off by default, and the JsonSerializerOptions.Strict preset added in .NET 10 enables it.