Find the null
The message never says which reference was null. The stack trace says where: the first frame of your code is the method, and with a PDB deployed, the file and line. On that line, every ., [ ] and method call on a reference can be the one. In order.Customer.Address.City.ToUpper(), any of order, Customer, Address or City can be null.
Common causes
- A lookup that found nothing.
FirstOrDefault,SingleOrDefault,Find, EF Core'sFindAsyncandDictionary.TryGetValue's out value are null when nothing matches. - An object that was never filled in. A property not set in the constructor or object initializer, a navigation property EF Core did not load (no
Include), or a JSON field missing from the request body. - A failed
ascast.x as Ordergives null when x is something else; a direct cast would throw InvalidCastException, which is easier to diagnose. - An array or collection that exists but holds nulls, such as
new string[3].
Prevent it
#nullable enable
Order? order = FindOrder(42);
// ?. stops at the first null and gives null; ?? supplies a default.
string city = order?.Customer?.Address?.City ?? "unknown";
Console.WriteLine(city); // prints unknown
// Fail early, with the parameter's name in the message, instead of deep inside.
try { Ship(order); }
catch (ArgumentNullException e) { Console.WriteLine(e.Message); } // prints Value cannot be null. (Parameter 'order')
static Order? FindOrder(int id) => null;
static void Ship(Order? order) { ArgumentNullException.ThrowIfNull(order); }
record Order(Customer? Customer);
record Customer(Address? Address);
record Address(string City);
With #nullable enable (or <Nullable>enable</Nullable> in the project, the default in new projects), the compiler warns with CS8602 when you dereference something that may be null, before it becomes this exception in production.
FAQ
What does "Object reference not set to an instance of an object" mean?
A variable, field, property or return value was null, and the code used one of its members (a method, property or indexer). It is the message of System.NullReferenceException, and it is the same in .NET Framework and every version of .NET.
How do I find which variable is null?
The first frame of your code in the stack trace gives the file and line. The message does not name the variable, so if the line has several dots, break at that line in the debugger and inspect each one, or split the expression into separate lines.
How do I prevent NullReferenceException?
Enable nullable reference types (<Nullable>enable</Nullable>) and fix the CS8602 warnings, check results of FirstOrDefault, Find and TryGetValue, use ?. and ?? where null is expected, and validate parameters with ArgumentNullException.ThrowIfNull.
Should I catch NullReferenceException?
No. It is a bug in the code, not a condition to handle. Find the null and fix the code or the data that produced it.