Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C#: NullReferenceException: Object reference not set

The message never names the null. Read the stack trace, enable nullable reference types, and use null-conditional access instead of guessing.

~5 min readC#
#csharp#nullreferenceexception#null-safety#debugging
Bold white headline reading NULL REFERENCE beside a cyan object crate with an amber empty handle slot.

Introduction & Quick Summary

A request fails with the least informative exception in .NET:

code
System.NullReferenceException: Object reference not set to an instance of an object. at Shop.Api.OrderService.Total(Order order) in /src/OrderService.cs:line 42 at Shop.Api.Controllers.OrdersController.Get(Guid id) in /src/OrdersController.cs:line 27

Quick answer: some reference was null when the code dereferenced it, and the runtime does not say which one. The stack trace gives the line, and the line may contain several candidates. Find the null by inspecting the values on that line, not by guessing, then remove the possibility: initialise the object, return an empty collection instead of null, or check at the boundary where the value enters.

csharp
// the dereference that throws var total = order.Items.Sum(i => i.Price * i.Quantity); // explicit about the null case ArgumentNullException.ThrowIfNull(order); var total = order.Items?.Sum(i => i.Price * i.Quantity) ?? 0m;

This guide covers how to locate the actual null quickly, the constructs that produce one (uninitialised fields, FirstOrDefault, as, events with no subscribers), and how nullable reference types turn most of these failures into compiler warnings before the code ships.

Core Mechanics, Signatures & Reproducible Setup

NullReferenceException is thrown by the CLR when an instruction reads a member through a null reference. Because the check happens in the runtime, there is no variable name in the message; only the IL offset and the mapped source line are available.

csharp
record Item(string Name, decimal Price, int Quantity); class Order { public List<Item>? Items { get; set; } public Customer? Customer { get; set; } } static decimal Total(Order order) => order.Items.Sum(i => i.Price * i.Quantity); // NullReferenceException if Items is null

A reproducible project shows both the failure and the fix:

bash
dotnet new console -o nre && cd nre dotnet add package Microsoft.Extensions.Logging.Abstractions dotnet run
xml
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net8.0</TargetFramework> <Nullable>enable</Nullable> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> </PropertyGroup> </Project>

With <Nullable>enable</Nullable>, the compiler reports CS8602: Dereference of a possibly null reference on the order.Items line before the program ever runs. That warning is the real fix for the class of bug: it moves the discovery from a 3 a.m. alert to the build.

csharp
// the same line, written to be explicit static decimal Total(Order order) { ArgumentNullException.ThrowIfNull(order); if (order.Items is null) return 0m; return order.Items.Sum(i => i.Price * i.Quantity); }

Key Comparison Table

CauseTypical lineFix
field never assigned_repo.Save(x)initialise in constructor or use required
method returned nulluser.Profile.Namecheck the result, use ?.
FirstOrDefault on emptylist.First().IdFirstOrDefault()?.Id or check
as cast that failed(obj as User).Namepattern match with is
event with no handlerChanged(this, e)Changed?.Invoke(this, e)
missing DI registration_svc.Do() where _svc is nullresolve in constructor, do not new
array element nullrows[0].Valuevalidate input collection
OperatorMeaningExample
?.access only if not nullorder?.Customer?.Name
?[]index only if not nullrows?[0]
??fallback when nullname ?? "unknown"
??=assign if nullcache ??= new()
!suppress the warningorder!.Items
ArgumentNullException.ThrowIfNullguard at a boundarymethod entry
WarningMeaningUsual fix
CS8602dereference of possibly nullguard or ?.
CS8600converting null to non-nullablecheck the source
CS8603possible null returnreturn non-null or change signature
CS8618non-nullable field uninitialisedconstructor or required
CS8625null assigned to non-nullablefix the caller
CS8604possible null argumentguard before the call

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Locate the null in one minute

Read the top frame, open that line, and inspect every value on it. In a debugger, a conditional breakpoint on the line with order.Items == null skips straight to the failing call:

csharp
// useful in logs when the exception is caught catch (NullReferenceException ex) { logger.LogError(ex, "order {OrderId} failed, items null: {IsNull}", orderId, order?.Items is null); throw; }

When the stack trace points into framework code, the null came from an argument passed in; walk one frame up. The exception's StackTrace property includes file and line only when PDBs ship with the build, so set <DebugType>portable</DebugType> and keep the .pdb files next to the assemblies in production deployments — without them the trace is a list of method names.

2. Fields that were never initialised

A non-nullable field without an assignment compiles with CS8618, and at runtime holds null:

csharp
public class ReportService { private readonly IClock _clock; // CS8618 public ReportService() { } // forgot to assign }

Initialise in the constructor, use a primary constructor, or mark the property required so the compiler forces callers to supply it:

csharp
public class ReportService(IClock clock) { private readonly IClock _clock = clock ?? throw new ArgumentNullException(nameof(clock)); } public class Settings { public required string Endpoint { get; init; } }

required members are validated by the compiler at every object initialiser, which catches the missing assignment at the call site rather than at first use.

3. Methods and APIs that return null

FirstOrDefault, SingleOrDefault, Find, as, GetValueOrDefault, JsonSerializer.Deserialize, and HttpContext.Items["x"] all return null on a miss. The dereference is usually a few lines away from the call:

csharp
var user = users.FirstOrDefault(u => u.Email == email); return user.Profile.Name; // null when the user does not exist // explicit if (user is null) return Results.NotFound(); return user.Profile?.Name ?? user.Email;

Dictionary lookups have the same trap with [], while TryGetValue makes the miss visible:

csharp
if (cache.TryGetValue(key, out var entry) && entry is not null) { return entry; }

When the source is JSON, deserialisation can leave properties null even though the type says otherwise; check a payload with the JSON formatter before assuming the mapping is wrong.

4. Events and delegates

An event with no subscribers is null, and invoking it throws inside the class that raised it:

csharp
public event EventHandler<OrderSavedEventArgs>? Saved; protected virtual void OnSaved(OrderSavedEventArgs e) => Saved?.Invoke(this, e);

The nullable annotation plus ?.Invoke is the idiomatic pair. Copying the delegate to a local before invoking avoids a race where a subscriber unsubscribes between the null check and the call:

csharp
var handler = Saved; handler?.Invoke(this, e);

5. Collections, indexers and LINQ chains

An empty collection is safe; a collection containing null entries is not. Validation belongs at the boundary where data enters the system:

csharp
static decimal SumRows(IEnumerable<Row?> rows) => rows.Where(r => r is not null).Sum(r => r!.Amount);

For arrays of reference types the default value of each element is null; new string[10] contains ten nulls, not ten empty strings. Array.Empty<T>() and Enumerable.Empty<T>() are better defaults than null for "no results" because callers iterate without a guard.

6. Adopt nullable reference types without a rewrite

Turning <Nullable>enable</Nullable> on a large solution produces hundreds of warnings. Warnings-as-errors on new code plus #nullable enable at the top of files being touched is a workable migration:

csharp
#nullable enable public sealed class Pricing { public decimal Discount(Customer? customer) => customer?.Tier switch { "gold" => 0.15m, "silver" => 0.10m, _ => 0m, }; }

Attributes help annotate contracts the compiler cannot infer: [NotNullWhen(true)] on TryGet methods, [MaybeNull] on out parameters, and [MemberNotNull] on helpers that initialise fields. Stack traces pasted into a report can be searched with the regex tester to count which call sites recur, which is a cheap way to prioritise the first files to convert.

Common Compilation/Runtime Mistakes & Version Gotchas

  • Catching and swallowing it. catch (NullReferenceException) { } hides a logic error; either fix the source of the null or let it surface.
  • Using ! to silence the compiler. The null-forgiving operator asserts a fact the runtime will check anyway; it converts a warning into the same exception later.
  • Assuming as throws. It returns null on failure, unlike a cast, so the exception appears on the next line.
  • Blaming the framework. When the failing frame is inside a library, the null argument or null field almost always originates in the caller.
  • Version notes. ArgumentNullException.ThrowIfNull arrived in .NET 6. Nullable reference types are annotations only: no runtime check is added, so a library built without them can still hand you null. Debug builds since .NET Core 3 stop at the exact dereference instead of showing an offset inside a larger method, which makes local debugging easier than the production trace suggests.
  • async void handlers. An exception in an async void method is raised on the synchronization context and cannot be awaited; prefer async Task, where the faulted task carries the exception.

Official documentation: NullReferenceException and member access and null-conditional operators.

Official references

primary documentation

The C# documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.