System.NullReferenceException: Object reference not set to an instance of an object
You’re accessing a member of an object that’s null.
Fix 1: Null check
// ❌ user might be null
var name = user.Name;
// ✅ Null check
if (user != 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.
Related: C# Cannot Implicitly Convert Type — How to Fix It Related: C# StackOverflowException — How to Fix It