C# NullReferenceException β Object Reference Not Set β How to Fix It
System.NullReferenceException: Object reference not set to an instance of an object
Youβre accessing a member of an object thatβs null.
Why this happens
In C#, reference types default to null when not explicitly initialized. When you call a method or access a property on a null object, the runtime throws this exception. Itβs the most common .NET exception and typically indicates a missing initialization, an unexpected null return from a method, or a failed lookup like FirstOrDefault() returning null.
Fix 1: Null check
// β user might be null
var name = user.Name;
// β
Null-conditional operator (C# 6+)
var name = user?.Name;
var name = user?.Name ?? "Unknown";
Fix 2: Initialize objects
// β Not initialized
List<string> items;
items.Add("hello"); // NullReferenceException!
// β
Initialize
List<string> items = new List<string>();
items.Add("hello");
Fix 3: Enable nullable reference types
// In .csproj
<Nullable>enable</Nullable>
The compiler will warn you about potential null references.
Alternative solutions
Use pattern matching (C# 9+) for cleaner null checks:
if (user is { Name: var name, Email: var email })
{
Console.WriteLine($"{name} ({email})");
}
You can also use the required keyword (C# 11+) on properties to enforce initialization at construction time.
Prevention
- Enable
<Nullable>enable</Nullable>in every new project from the start β the compiler warnings catch most null issues at build time. - Always validate return values from methods that can return
null, especially LINQ methods likeFirstOrDefault().
Related: C# Cannot Implicitly Convert Type β How to Fix It Β· C# StackOverflowException β How to Fix It