NullReferenceException 🟪 .NET

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

  1. Find the line in the stack trace (enable PDBs in release)
  2. Use ?. and ??
  3. Check FirstOrDefault() results
  4. Enable nullable reference types

Detailed fix by platform

.NET

  1. 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

  1. Line — Which expression?
  2. 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.