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 NullReferenceException often happens because of one of these:
- A variable was declared but never initialized.
- A method returned
nulland the result was used immediately. - A property inside an object chain was
null. - A collection contained a
nullitem. - Dependency injection or setup code did not assign a required object.
- Data from an API or database was missing.
Important idea
null is not the same as an empty object.
For example:
string a = null;
string b = "";
apoints to no string at all.bpoints to a real string object that just contains no characters.
Only a can cause a NullReferenceException when you access members directly.
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:
- if
personis not null, getName - if
personis null, returnnullinstead of throwing
Using the null-coalescing operator
Person person = GetPerson();
string name = person?.Name ?? "Unknown";
Console.WriteLine(name);
This gives a fallback value when person or person.Name is null.
Chained access example
Console.WriteLine(order.Customer.Address.City);
Any part of this chain could be null:
orderorder.Customerorder.Customer.Address
Safer version:
Console.WriteLine(order?.Customer?.Address?.City ?? "No city available");
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(10);
Console.WriteLine(person.Name);
Possible execution:
FindPersonById(10)searches for a person.- No matching person is found.
- The method returns
null. personbecomesnull.person.Nameis evaluated.- Exception is thrown.
How to debug it
When you see a line like this:
Console.WriteLine(order.Customer.Address.City);
Check each part separately:
Console.WriteLine(order == null);
Console.WriteLine(order?.Customer == null);
Console.WriteLine(order?.Customer?.Address == null);
This helps identify exactly which reference is null.
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.
foreach (var customer in customers)
{
string email = customer?.Email ?? "no-email@example.com";
}
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.
if (request == null || request.Items == null)
{
return BadRequest();
}
Safe navigation in object graphs
For nested objects, null-conditional access keeps code concise.
var city = order?.Customer?.Address?.City;
Constructor initialization
Required dependencies should be assigned when the object is created.
public class OrderService
{
private readonly IOrderRepository _repository;
public OrderService(IOrderRepository repository)
{
_repository = repository ?? throw new ArgumentNullException(nameof(repository));
}
}
Nullable reference types
Modern C# can warn you at compile time about possible null problems.
string? name = GetName();
Console.WriteLine(name?.Length);
This helps catch issues before runtime.
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, butCustomerorAddressmay still be null.
Fix:
Console.WriteLine(order?.Customer?.Address?.City ?? "Unknown");
4. Confusing null with empty values
Broken assumption:
string text = null;
if (text.Length == 0)
{
Console.WriteLine("Empty");
}
Fix:
if (string.IsNullOrEmpty(text))
{
Console.WriteLine("Null or empty");
}
5. Catching the exception instead of fixing the cause
Broken approach:
try
{
Console.WriteLine(person.Name);
}
catch (NullReferenceException)
{
Console.WriteLine("Something was null");
}
Why this is a mistake:
- It hides the real bug.
- It does not explain why the value was null.
- Prevention is better than reacting after failure.
Better:
- find the null source
- initialize the object correctly
- validate input
- use null-safe operators when appropriate
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 |
?. | Null-conditional access | No, returns null instead | Safe chained access |
?? | Fallback value when null | No | Defaults and failover |
ArgumentNullException | You throw this when input should not be null | Not the same exception | Validation of method arguments |
NullReferenceException vs ArgumentNullException
NullReferenceExceptionmeans your code tried to use a null object.ArgumentNullExceptionis usually thrown intentionally to say a caller passed an invalid null argument.
Manual checks vs null-safe operators
Manual check:
if (person != null)
{
Console.WriteLine(person.Name);
}
Null-safe operator:
Console.WriteLine(person?.Name);
Use manual checks when you need custom logic. Use ?. when you just need safe access.
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
Example:
settings ??= new Settings();
Debug checklist
- Which exact line throws the exception?
- Which variable on that line is null?
- Was the object initialized?
- Did a method return null?
- Is part of a property chain null?
- Should null be allowed here?
Good habits
- Initialize required objects early.
- Validate method parameters.
- Use nullable reference types where possible.
- Do not assume external data is complete.
- Prefer empty collections over null collections when practical.
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?
Because another object later in the access chain may be null. For example, order may exist while order.Customer does not.
Should methods return null?
Sometimes, but only when that meaning is clear and expected. In many cases, returning an empty collection, a default value, or a result object is safer.
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.
Best Way to Repeat a Character in C#: Building Repeated Strings Efficiently
Learn the best way to repeat a character in C#, compare StringBuilder, string concatenation, and simpler built-in options.
C# Access Modifiers and static: public, private, protected, and Defaults
Learn how C# public, private, protected, and default access control visibility, and how static differs from instance members.