NullReferenceException
debugging
programming
error handling
C#

What is a NullReferenceException, and how do I fix it?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

A NullReferenceException in C# means your code tried to use an object reference that was null. In plain terms, you asked for a member such as a property, field, method, or index on something that does not point to a real object.

The fix is rarely "catch the exception and continue." The real fix is to find out why the value was null in the first place and then make that state impossible, expected, or safely handled.

What Actually Throws It

These all throw NullReferenceException:

csharp
string? name = null;
Console.WriteLine(name.Length);
csharp
Person? person = null;
Console.WriteLine(person.Address.City);
csharp
int[]? numbers = null;
Console.WriteLine(numbers[0]);

In each case, the variable itself is not the problem. The problem is that the variable contains no object reference at runtime.

The First Job: Find Which Value Is Null

When you see a long expression such as order.Customer.Address.City, the exception means one link in that chain was null, not necessarily the first variable.

Break it apart:

csharp
var customer = order.Customer;
var address = customer.Address;
var city = address.City;

Or inspect it in the debugger. That tells you whether order, Customer, or Address is the missing value.

This is the most important debugging step because it turns a vague crash into a concrete cause.

Fix by Initializing Required Objects

If a value is required for the object to be valid, initialize it before use:

csharp
1public class Address
2{
3    public string City { get; set; } = "";
4}
5
6public class Person
7{
8    public string Name { get; set; } = "";
9    public Address Address { get; set; } = new Address();
10}

Now this no longer throws:

csharp
var person = new Person();
Console.WriteLine(person.Address.City);

This is often the best fix for domain objects that should never be partially initialized.

Fix by Guarding Optional Values

Sometimes null is valid and means "missing" or "not found." In that case, guard it explicitly:

csharp
1Person? person = FindPerson();
2
3if (person is null)
4{
5    Console.WriteLine("No person found");
6    return;
7}
8
9Console.WriteLine(person.Name);

Or use the null-conditional and null-coalescing operators when a fallback makes sense:

csharp
string city = person?.Address?.City ?? "unknown";
Console.WriteLine(city);

That does not make null disappear. It just handles it intentionally.

Throw the Right Exception at Boundaries

If a method requires a non-null argument, fail early with ArgumentNullException instead of letting a later NullReferenceException happen deeper inside:

csharp
1public static int CountCharacters(string text)
2{
3    ArgumentNullException.ThrowIfNull(text);
4    return text.Length;
5}

This produces a clearer error message and points directly at the broken contract.

Nullable Reference Types Help Prevent It

Modern C# can warn you about potential null misuse before runtime when nullable reference types are enabled:

csharp
1#nullable enable
2
3string? maybeName = null;
4// Warning: possible null dereference
5Console.WriteLine(maybeName.Length);

The compiler warning is not the same as runtime safety, but it catches many problems much earlier.

Do Not Treat Catching It as the Main Fix

This is usually the wrong instinct:

csharp
1try
2{
3    Console.WriteLine(person.Address.City);
4}
5catch (NullReferenceException)
6{
7    Console.WriteLine("Something was null");
8}

That hides the real bug. Exceptions are for exceptional situations, not for normal null-driven control flow. Prefer validation, initialization, or explicit optional handling.

Common Pitfalls

The most common pitfall is debugging the line but not the source. The crash may occur at person.Address.City, but the real mistake might be that a repository returned null earlier and nobody handled it.

Another is assuming object creation initializes nested objects automatically. new Person() does not magically create Address unless your class does so.

Teams also ignore nullable warnings from the compiler. Those warnings exist because the runtime exception is expensive and avoidable.

Finally, catching NullReferenceException broadly is almost always a poor substitute for fixing the data flow.

Summary

  • 'NullReferenceException means your code dereferenced a null object reference.'
  • Find the exact missing value before choosing a fix.
  • Initialize required objects so invalid states are harder to create.
  • Guard optional values explicitly with checks or null-aware operators.
  • Use nullable reference types and ArgumentNullException to catch problems earlier and more clearly.

Course illustration
Course illustration

All Rights Reserved.