C# NullReferenceException Fix
In this tutorial, you'll learn about C# NullReferenceException Fix. We cover key concepts, practical examples, and best practices.
The Problem
Your C# application crashes with:
System.NullReferenceException: Object reference not set to an instance of an object.
at MyApp.Program.Main() in C:\src\Program.cs:line 12
A NullReferenceException (NRE) occurs when you try to access a member (property, method, field) on a variable that is null. This is the most common runtime exception in C# and always means a reference was not initialized before use.
Quick Fix
Step 1: Find what is null
The stack trace shows the file and line number. Open the file and identify all nullable references on that line:
// Line 12
Console.WriteLine(person.Name.ToUpper());
Any of these could be null: person, person.Name, or the return of ToUpper(). Break it down:
if (person != null && person.Name != null)
{
Console.WriteLine(person.Name.ToUpper());
}
Step 2: Initialize properties in constructors
WRONG -- property never initialized:
public class OrderService
{
private PaymentGateway _gateway; // null
public void ProcessOrder(Order order)
{
_gateway.Charge(order.Total); // NullReferenceException
}
}
RIGHT -- initialize in constructor or inline:
public class OrderService
{
private readonly PaymentGateway _gateway;
public OrderService(PaymentGateway gateway)
{
_gateway = gateway ?? throw new ArgumentNullException(nameof(gateway));
}
public void ProcessOrder(Order order)
{
_gateway.Charge(order.Total);
}
}
Step 3: Use the null-conditional operator
WRONG -- verbose null check for chained calls:
if (person != null && person.Address != null && person.Address.City != null)
{
var city = person.Address.City.ToUpper();
}
RIGHT -- use ?. (null-conditional):
var city = person?.Address?.City?.ToUpper();
Combine with ?? for a default:
var city = person?.Address?.City?.ToUpper() ?? "UNKNOWN";
Step 4: Use the null-forgiving operator (only when certain)
Use ! when you are absolutely sure the value is not null:
public void Process(string message)
{
var length = message!.Length; // suppresses CS8602 warning
}
Only use ! when you know something the compiler does not. Overusing it defeats the purpose of nullable reference types.
Step 5: Enable nullable reference types
In .NET 6+, enable nullable reference types in your project file:
<PropertyGroup>
<Nullable>enable</Nullable>
</PropertyGroup>
The compiler warns about potential null dereferences at compile time instead of runtime:
#nullable enable
string name = null; // CS8625: Cannot convert null literal to non-nullable reference type
string? optional = null; // OK -- nullable
Console.WriteLine(optional.Length); // CS8602: Dereference of a possibly null reference
Step 6: Check LINQ queries for null returns
WRONG -- FirstOrDefault can return null:
var user = users.FirstOrDefault(u => u.Id == id);
Console.WriteLine(user.Name); // NullReferenceException if no user matches
RIGHT -- check before use:
var user = users.FirstOrDefault(u => u.Id == id);
if (user != null)
{
Console.WriteLine(user.Name);
}
else
{
Console.WriteLine("User not found");
}
Or use First() instead when you expect a result:
var user = users.First(u => u.Id == id); // throws InvalidOperationException if no match
Use DodaTech's .NET Analyzer to scan for potential null dereferences and suggest null-conditional operators across your codebase.
Prevention
- Enable nullable reference types (
<Nullable>enable</Nullable>) in all new projects. - Initialize all properties in constructors or use constructor injection.
- Use the null-conditional operator
?.for chained access. - Use
ArgumentNullException.ThrowIfNull()for parameter validation (.NET 6+). - Use
FirstOrDefaultwith null checks, orFirstwhen the element must exist. - Configure analyzers to treat nullability warnings as errors.
Common Mistakes with nullreference
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
These mistakes appear frequently in real-world CSHARP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro