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.

Introduction & Quick Summary
A request fails with the least informative exception in .NET:
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 27Quick 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.
// 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.
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 nullA reproducible project shows both the failure and the fix:
dotnet new console -o nre && cd nre
dotnet add package Microsoft.Extensions.Logging.Abstractions
dotnet run<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.
// 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
| Cause | Typical line | Fix |
|---|---|---|
| field never assigned | _repo.Save(x) | initialise in constructor or use required |
| method returned null | user.Profile.Name | check the result, use ?. |
FirstOrDefault on empty | list.First().Id | FirstOrDefault()?.Id or check |
as cast that failed | (obj as User).Name | pattern match with is |
| event with no handler | Changed(this, e) | Changed?.Invoke(this, e) |
| missing DI registration | _svc.Do() where _svc is null | resolve in constructor, do not new |
| array element null | rows[0].Value | validate input collection |
| Operator | Meaning | Example |
|---|---|---|
?. | access only if not null | order?.Customer?.Name |
?[] | index only if not null | rows?[0] |
?? | fallback when null | name ?? "unknown" |
??= | assign if null | cache ??= new() |
! | suppress the warning | order!.Items |
ArgumentNullException.ThrowIfNull | guard at a boundary | method entry |
| Warning | Meaning | Usual fix |
|---|---|---|
CS8602 | dereference of possibly null | guard or ?. |
CS8600 | converting null to non-nullable | check the source |
CS8603 | possible null return | return non-null or change signature |
CS8618 | non-nullable field uninitialised | constructor or required |
CS8625 | null assigned to non-nullable | fix the caller |
CS8604 | possible null argument | guard 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:
// 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:
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:
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:
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:
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:
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:
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:
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:
#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
asthrows. 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.ThrowIfNullarrived 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 voidhandlers. An exception in anasync voidmethod is raised on the synchronization context and cannot be awaited; preferasync Task, where the faulted task carries the exception.
Official documentation: NullReferenceException and member access and null-conditional operators.
Official references
primary documentationThe C# documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related C# guides
All C# guidesC# CS0117: 'X' does not contain a definition for 'Y'
CS0117 means the compiled assembly has no such member, usually from an older target framework or package. Check the API surface before editing code.
C# CS0246: The type or namespace name could not be found
CS0246 is a compile-time resolution failure: a missing using, package, target framework, or an unrestored project. Trace it backward from the symbol.
CS1061: does not contain a definition for and no extension method
Member lookup failed on both instance and extension methods. Type inference, missing using directives, target frameworks and packages explain most cases.
.NET: The framework 'Microsoft.NETCore.App' was not found
A framework-dependent app asks for a runtime major that is absent. Install the matching runtime or publish self-contained, and match Docker tags.
More in C#
All C# guidesThe guides filed next to this one in C#, in library order.