Find a null reference and repair its input contract

A NullReferenceException means code tried to use an object through a null reference. On a line such as order.Customer.Address.City, several references can be responsible. Fix the missing-data contract at its source rather than adding a catch that lets the program continue with incomplete state.

C# nullable annotations help detect mistakes during compilation. They do not, by themselves, prevent external data, reflection or older libraries from supplying null. A declared non-nullable property is an intent that your boundaries must enforce.

Reproduce a boundary failure

Create a .NET 10 console project with dotnet new console -n NullDemo -f net10.0. Keep nullable reference types enabled, replace Program.cs, and run dotnet run --project NullDemo from its parent directory.

C#
using System;
using System.IO;
using System.Text.Json;

var order = JsonSerializer.Deserialize<Order>("""{"Customer":null}""")
	?? throw new InvalidDataException("Missing order.");
try {
	Console.WriteLine(order.Customer.Address.City);
} catch (NullReferenceException) {
	Console.WriteLine("Unsafe access failed");
}

try {
	Console.WriteLine(RequireCity(order));
} catch (InvalidDataException ex) {
	Console.WriteLine(ex.Message);
}
Console.WriteLine($"Optional display={order.Customer?.Address?.City ?? "Unknown"}");
Console.WriteLine(RequireCity(new Order(new Customer(new Address("Brisbane")))));

static string RequireCity(Order order) {
	ArgumentNullException.ThrowIfNull(order);
	var customer = order.Customer
		?? throw new InvalidDataException("Missing customer.");
	var address = customer.Address
		?? throw new InvalidDataException("Missing address.");
	if (string.IsNullOrWhiteSpace(address.City)) {
		throw new InvalidDataException("Missing city.");
	}
	return address.City;
}

sealed record Order(Customer Customer);
sealed record Customer(Address Address);
sealed record Address(string City);

Expected output:

Plain text
Unsafe access failed
Missing customer.
Optional display=Unknown
Brisbane

The first catch exists only to keep the deliberate reproduction running. The repair is the second path, which rejects invalid required data with a specific message. The optional display path demonstrates a different policy, where absence is acceptable and “Unknown” is a meaningful fallback.

Locate the actual dereference

In Visual Studio, open Debug → Windows → Exception Settings and enable breaking when System.NullReferenceException is thrown. Reproduce the problem and inspect the failing frame. Examine each reference on the line and the local variables that produced it. Do not assume the final property name is the null object.

For a complicated expression, temporarily split it into named intermediate values. That exposes whether the order, customer or address was absent. Inspect the call stack and trace the value back to its origin, such as a missing lookup result, uninitialized field, failed deserialization or disposed lifecycle owner.

Choose the appropriate contract

For required data, reject the input before starting work that depends on it. The sample's RequireCity method checks both missing objects and an empty city. It communicates a domain-relevant failure instead of allowing an unrelated dereference to fail later.

For optional data, model it as nullable and use ?. or an explicit branch. Choose a fallback only when that value makes sense to the caller. Creating empty objects everywhere can hide a broken payload and move the failure to a later operation.

The null-forgiving operator ! changes compiler analysis. It does not insert a runtime guard. Similarly, changing a property from string? to string does not validate deserialized data. Current System.Text.Json can enforce some nullable annotations when configured, but required fields, collection elements and business constraints still need deliberate handling.

Test the valid case and each missing required level separately. For concurrent or event-driven code, also inspect ownership and timing. A value checked earlier may no longer represent the state needed by a later operation. The small deterministic example verifies data validation, while diagnosing an actual race requires evidence from the application's execution.

References

Nullable reference types - C#
Use nullable reference types to express your intent about which variables can be null. The compiler then warns when your code might dereference null.
https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/null-safety/nullable-reference-types
NullReferenceException Class (System)
The exception that is thrown when there is an attempt to dereference a null object reference.
https://learn.microsoft.com/en-us/dotnet/api/system.nullreferenceexception?view=net-10.0
Manage exceptions with the debugger - Visual Studio (Windows)
Learn how to specify which exceptions the debugger breaks on, at which point you want the debugger to break, and how breaks are handled.
https://learn.microsoft.com/en-us/visualstudio/debugger/managing-exceptions-with-the-debugger?view=visualstudio

Question provenance

This article addresses What is a NullReferenceException, and how do I fix it? , asked by John Saunders on Stack Overflow. The source question is licensed under CC BY-SA 3.0 . The explanation and examples here are newly authored for current .NET. No answer text or code is reproduced.

Author: Herman Schoenfeld