Question
What Is a NullReferenceException in C# and How Do You Fix It?
Question
I have some C# code that throws a NullReferenceException with the message:
Object reference not set to an instance of an object.
What does this error mean, why does it happen, and how can I identify and fix the code that is causing it?
Short Answer
By the end of this page, you will understand what NullReferenceException means in C#, why it occurs, how to trace the null value that caused it, and how to prevent similar errors using null checks, proper initialization, and safer language features.
Concept
NullReferenceException is one of the most common runtime errors in C#.
It happens when your code tries to use an object reference that is currently null.
In C#, many variables do not directly hold an object. Instead, they hold a reference to an object in memory. If that reference points to nothing, its value is null.
When you try to do something with that missing object, such as:
- access a property
- call a method
- index into an object
- use a field
the runtime cannot continue, so it throws a NullReferenceException.
Example
string name = null;
Console.WriteLine(name.Length);
name does not refer to an actual string object, so name.Length fails.
Why this matters
Null-related bugs are common in real applications because data often comes from outside your code:
- user input
- databases
- APIs
- configuration files
- optional fields
- objects created in different parts of the system
If you assume a value exists when it does not, your program can crash at runtime.
Common causes
A often happens because of one of these:
Mental Model
Think of a reference variable as a piece of paper with a house address written on it.
- If the paper contains a valid address, you can go to the house and interact with it.
- If the paper is blank, that is like
null. - Trying to visit the house using a blank address makes no sense.
That is what happens with a NullReferenceException: your code tries to go to an object that does not exist.
Another way to think about it:
- an object = a real box
- a reference = a label pointing to the box
null= the label points nowhere
If you try to open the box through a label that points nowhere, the program fails.
Syntax and Examples
Basic null problem
Person person = null;
Console.WriteLine(person.Name);
This throws NullReferenceException because person does not refer to a Person object.
Fix by creating the object
Person person = new Person();
person.Name = "Ava";
Console.WriteLine(person.Name);
Now person points to a real object, so accessing Name is safe.
Fix by checking for null
Person person = GetPerson();
if (person != null)
{
Console.WriteLine(person.Name);
}
This avoids the exception if GetPerson() returns null.
Using the null-conditional operator
Person person = GetPerson();
Console.WriteLine(person?.Name);
person?.Name means:
Step by Step Execution
Consider this code:
class Person
{
public string Name { get; set; }
}
Person person = null;
Console.WriteLine(person.Name);
Step-by-step
-
Person person = null;- The variable
personis created. - It does not point to any
Personobject. - Its value is
null.
- The variable
-
Console.WriteLine(person.Name);- The runtime first tries to evaluate
person.Name. - To get
Name, it must look at the actualPersonobject. - But
personpoints to nothing. - C# throws
NullReferenceException.
- The runtime first tries to evaluate
A more realistic example
Person person = FindPersonById();
Console.WriteLine(person.Name);
Real World Use Cases
Null handling appears in almost every type of C# application.
Web applications
A controller may expect a user record from the database, but the record might not exist.
var user = repository.GetUser(id);
if (user == null)
{
return NotFound();
}
API responses
External APIs may omit fields or return partial data.
string city = response?.Customer?.Address?.City ?? "Unknown";
Desktop or mobile apps
A UI control or selected item may not exist yet.
if (listBox.SelectedItem != null)
{
Console.WriteLine(listBox.SelectedItem.ToString());
}
Configuration loading
A setting may be missing from configuration.
string connectionString = config["ConnectionString"]
?? throw new InvalidOperationException("Missing connection string.");
Data processing
Imported records can contain missing values.
Real Codebase Usage
In real projects, developers usually do more than just add random null checks. They use clear patterns.
Guard clauses
Guard clauses stop execution early when required values are missing.
public void SendEmail(Customer customer)
{
if (customer == null)
throw new ArgumentNullException(nameof(customer));
if (string.IsNullOrWhiteSpace(customer.Email))
throw new ArgumentException("Email is required.");
// continue safely
}
Early returns
Useful when a missing object is a valid situation.
public string GetDisplayName(User user)
{
if (user == null)
return "Guest";
return user.Name;
}
Validation at boundaries
Check incoming data from requests, files, or APIs before deeper logic uses it.
(request == || request.Items == )
{
BadRequest();
}
Common Mistakes
1. Declaring without creating
Broken code:
Person person;
Console.WriteLine(person.Name);
Problem:
- Local variables must be assigned before use.
- Even if assigned
null, accessing members will fail.
Fix:
Person person = new Person();
Console.WriteLine(person.Name);
2. Assuming a method never returns null
Broken code:
Person person = repository.FindById(5);
Console.WriteLine(person.Name);
Fix:
Person person = repository.FindById(5);
if (person != null)
{
Console.WriteLine(person.Name);
}
3. Only checking the first object in a chain
Broken code:
if (order != null)
{
Console.WriteLine(order.Customer.Address.City);
}
Problem:
ordermay exist, butCustomeror may still be null.
Comparisons
| Concept | What it means | Throws NullReferenceException? | Typical use |
|---|---|---|---|
null | No object exists | Yes, if you access members directly | Optional or missing values |
Empty string "" | A real string with no characters | No | Text input with no content |
Empty list new List<int>() | A real collection with zero items | No | Safe collection initialization |
Null check if (x != null) | Manual protection before use | No, if used correctly | Clear control flow |
?. |
Cheat Sheet
Quick reference
What causes NullReferenceException
You used a member on a variable whose value is null.
obj.Method();
obj.Property;
obj.Field;
obj[index];
If obj == null, these can fail.
Common fixes
if (obj != null)
{
obj.Method();
}
obj?.Method();
string name = obj?.Name ?? "Default";
_myService = service ?? throw new ArgumentNullException(nameof(service));
Operators to know
?.safe member access?[]safe index access??fallback when null??=assign only if null
FAQ
What does Object reference not set to an instance of an object mean?
It means your code tried to use an object variable that currently has the value null instead of pointing to a real object.
How do I find which object is null?
Look at the exact line in the stack trace or debugger. If the line contains chained access like order.Customer.Address.City, inspect each part until you find the null one.
Can value types cause NullReferenceException?
Normal value types like int do not behave like reference types. But nullable value types or boxed values can still be involved in null-related logic.
How do I prevent NullReferenceException in C#?
Use proper initialization, validate inputs, check for null when needed, and use features like ?., ??, and nullable reference types.
Is it okay to catch NullReferenceException?
Usually no. It is better to fix the root cause. Catching it often hides a bug instead of solving it.
What is the difference between null and an empty object?
null means no object exists. An empty object is still a real object, just with default or empty values.
Why do I still get null errors after checking one variable?
Mini Project
Description
Build a small C# console program that safely prints customer information from possibly incomplete data. This project demonstrates how NullReferenceException happens with nested objects and how to prevent it using initialization, null checks, and null-safe operators.
Goal
Create a program that displays a customer's name and city without crashing when some data is missing.
Requirements
- Create
CustomerandAddressclasses. - Allow
Addressto be missing for some customers. - Print the customer's name and city safely.
- Show a default message when the city is unavailable.
- Avoid any
NullReferenceExceptionduring output.
Keep learning
Related questions
AddTransient vs AddScoped vs AddSingleton in ASP.NET Core Dependency Injection
Learn the differences between AddTransient, AddScoped, and AddSingleton in ASP.NET Core DI with examples and practical usage.
C# Type Checking Explained: typeof vs GetType() vs is
Learn when to use typeof, GetType(), and is in C#. Understand exact type checks, inheritance, and safe type testing clearly.
C# Version Numbers Explained: C# vs .NET Framework and Why “C# 3.5” Is Incorrect
Learn the correct C# version numbers, how they map to .NET releases, and why terms like C# 3.5 are inaccurate and confusing.