System.NullReferenceException: Object reference not set to an instance of an object.
.NET · updated 2026-11-13
Thrown when C# code reads a member through a null reference. The message never says which reference, so the stack trace's first frame (with the line number when the PDB is deployed) is the clue: the null is one of the references used on that line.
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object. at Receipts.Email(Order o) in /app/Program.cs:line 9 at Program.<Main>$(String[] args) in /app/Program.cs:line 2
Quick fix
Open the first frame's line and list every reference it dereferences (o, o.Customer, o.Customer.Email). Find which can be null, then either handle it with ?. and ?? or make it non-null where it is created. With <Nullable>enable</Nullable> the compiler flags these lines as CS8602 'Dereference of a possibly null reference'; fixing those warnings removes most of these exceptions.
- Read the first stack frame; deploy the .pdb files so production traces carry line numbers.
- On that line, find the reference that was null: a navigation property, a dictionary or EF lookup, a deserialized DTO field.
- If null is normal, use ?. and ?? and handle the missing case.
- If it is a bug, guard where the object is created: ArgumentNullException.ThrowIfNull(x) or a required member.
- Set <Nullable>enable</Nullable> in the .csproj and treat CS8602 and CS8618 warnings as work items (or as errors).
// Can be missing: handle it
string? email = order.Customer?.Email?.ToLowerInvariant();
if (email is null) return Results.NotFound("order has no customer email");
// Must exist: fail where it is built
public record Customer(string Email)
{
public string Email { get; } = Email ?? throw new ArgumentNullException(nameof(Email));
}Paste this into Claude Code, Cursor or Codex in the project that throws it. The agent reads this guide in plain text and applies the fix that matches your stack.
Read https://runheed.com/errors/dotnet-nullreferenceexception.md and fix this error in this project.Why it happens
A lookup returned null
FirstOrDefault, FindAsync, a dictionary TryGetValue you ignored, or a cache miss returns null, and the next line uses it.
A navigation property was not loaded
In Entity Framework, order.Customer stays null unless the query includes it (Include) or lazy loading is on, so order.Customer.Email throws.
A deserialized field is missing
System.Text.Json leaves a property null when the JSON omits it, even for a non-nullable string, because deserialization does not enforce nullable annotations.
The null-forgiving operator hid it
x!.Member tells the compiler the value is not null; when it is, the warning that would have caught it is gone and the exception happens at run time.
Other fixes
- Add <WarningsAsErrors>nullable</WarningsAsErrors> so new possible null dereferences fail the build.
- Use required members (C# 11) for properties that must be set at construction.
- Validate request models with data annotations ([Required]) so a missing field is a 400 instead of an exception later.
Same error, other wording
- System.NullReferenceException: Object reference not set to an instance of an object.
- Object reference not set to an instance of an object. at Microsoft.EntityFrameworkCore...
- warning CS8602: Dereference of a possibly null reference.
Let your coding agent catch the next one
Runheed records this error in production with the stack trace, the breadcrumbs before it and, when you set it, the agent session that shipped the code, and serves it to Claude Code, Cursor or any MCP client. With it connected, you can ask:
> Find the NullReferenceException errors in production, open the first frame of the latest one, work out which reference was null and why, and fix it where it is loaded or created.
Setup for .NET and ASP.NET Core, then have your agent fix and resolve it.
Related errors
- java.lang.NullPointerException: Cannot invoke "String.toLowerCase()" because the return...
- TypeError: Cannot read properties of undefined (reading 'x')
- AttributeError: 'NoneType' object has no attribute 'x'
More in Undefined, None and type errors
- panic: assignment to entry in nil mapGo
- TypeError: slugify(): Argument #1 ($title) must be of type string, null givenPHP
- System.InvalidOperationException: Sequence contains no elements.NET
- panic: runtime error: invalid memory address or nil pointer dereferenceGo
- NoMethodError: undefined method 'email' for nilRuby
- TypeError: Cannot destructure property 'id' of 'undefined' as it is undefined.Node.js
- TypeError: Cannot convert undefined or null to objectNode.js
- TypeError: items is not iterableNode.js
- TypeError: x is not a functionNode.js
- TypeError: Client is not a constructorNode.js
- ReferenceError: x is not definedNode.js
- ERR_INVALID_ARG_TYPE: The "path" argument must be of type string. Received undefinedNode.js
- TypeError: 'NoneType' object is not subscriptablePython
- TypeError: 'NoneType' object is not iterablePython
- KeyError: 'email'Python
- TypeError: unhashable type: 'list'Python
- AttributeError: 'dict' object has no attribute 'name'Python
- IndexError: list index out of rangePython
- TypeError: unsupported operand type(s) for +: 'int' and 'str'Python
- ValueError: invalid literal for int() with base 10: ''Python
- TypeError: __init__() got an unexpected keyword argument 'proxies'Python
- UnboundLocalError: cannot access local variable 'total' where it is not associated with a...Python
- RuntimeError: dictionary changed size during iterationPython
- ValueError: too many values to unpack (expected 2)Python
- TypeError: 'str' object is not callablePython
References: .NET API: NullReferenceException, C#: Nullable reference types, C# compiler warning CS8602
Spotted a mistake? Email hello@greatwork.company. About Runheed.