System.NullReferenceException: Object reference not set to an instance of an object
Code dereferenced a variable that is null — the .NET equivalent of Java’s NullPointerException.
Seen on:
.NET
Meaning
The stack trace line shows where; enable nullable reference types (<Nullable>enable</Nullable>) so the compiler warns about possible nulls.
Common causes
- Uninitialized object or collection
- Method/LINQ returned null (
FirstOrDefault) - Dependency not registered in DI
- Model binding produced null
⚡ Quick fix
- Find the line in the stack trace (enable PDBs in release)
- Use
?.and?? - Check
FirstOrDefault()results - Enable nullable reference types
Detailed fix by platform
.NET
- Null-safe access:csharp
var city = user?.Address?.City ?? "Unknown"; var order = orders.FirstOrDefault(o => o.Id == id) ?? throw new KeyNotFoundException($"Order {id}");
How to diagnose
- Line — Which expression?
- Source — Where should the value come from?
🧠 Still stuck? Analyze your error
Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.
Was this page helpful?
Report a correction or suggest an improvement
Last updated 2 Oct 2026