πŸ”§ Error Fixes
Β· 1 min read

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 like FirstOrDefault().

Related: C# Cannot Implicitly Convert Type β€” How to Fix It Β· C# StackOverflowException β€” How to Fix It