How do I fix a NullReferenceException in C#?
You dereferenced a null reference. Read the stack trace for the line, then work out which of the values on that line is null — usually an uninitialised field or an unfound lookup.
#Find it
The stack trace names the file and line. On that line, one of the things before a . is null. In .NET 6+ the message usually names it directly:
Object reference not set to an instance of an object.
at Calculator.Calculate() in Form1.cs:line 42#The usual suspects
An uninitialised field. Reference type fields default to null:
private List<int> _scores; // null until assigned
private List<int> _scores = new(); // fixA lookup that found nothing:
var user = users.FirstOrDefault(u => u.Id == id); // null when no match
Console.WriteLine(user.Name); // boomA control referenced before the designer created it — in WinForms, code in the constructor that runs before InitializeComponent().
A missing config value. Configuration["Key"] returns null for an absent key.
#Guard it
if (user is not null)
Console.WriteLine(user.Name);
Console.WriteLine(user?.Name ?? "Unknown");#Turn on nullable reference types
In your .csproj:
<Nullable>enable</Nullable>Now the compiler distinguishes string from string? and warns when you dereference something that might be null. This converts a runtime crash into a compile-time warning, which is the single highest-value setting in a modern C# project.
#Fail loudly at the boundary
ArgumentNullException.ThrowIfNull(user);Better to throw at the entry point, naming the parameter, than to let null travel three layers deeper and crash somewhere unrelated.