C# NullReferenceException
NullReferenceException is thrown in C# when an application tries to access an instance member through a reference whose value is null. The member may be a method, property, field, indexer, or event.
A null reference does not point to an object instance. For example, a string variable can exist while its value is null. Calling Substring(), reading Length, or accessing another instance member through that variable causes the exception.
Example That Recreates C# NullReferenceException
Following is a simple example to recreate the scenario where NullReferenceException is thrown.
Program.cs
using System;
namespace CSharpExamples {
class Program {
static void Main(string[] args) {
string str = null;
Console.WriteLine(str.Substring(5));
}
}
}
Here we defined a string with null value. When we try to access a method like Substring() on the string variable with null, NullReferenceException is thrown as shown in the following output.
Output
PS D:\workspace\csharp\HelloWorld> dotnet run
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
at CSharpExamples.Program.Main(String[] args) in D:\workspace\csharp\HelloWorld\Program.cs:line 8
The failing expression is str.Substring(5). The problem occurs before Substring() can process its argument because str does not refer to a string instance.
Common Causes of NullReferenceException in C#
A NullReferenceException usually indicates that a value was not initialized, was unexpectedly returned as null, or became null before it was used. Common situations include:
- Calling a method on a null string or class reference.
- Reading a property from a null object.
- Accessing a member through a null object inside a nested expression.
- Using an array element, collection item, or dictionary value that is null.
- Assuming that a method, query, deserializer, or dependency always returns an object.
- Leaving a field or property uninitialized before another method uses it.
NullReferenceException in a Nested Property Chain
Long member-access chains can make the source of a null reference less obvious. In the following expression, either customer or customer.Address could be null:
string city = customer.Address.City;
Inspect each reference in the chain separately while debugging. Breaking the expression into smaller statements can reveal which value is null.
Address address = customer.Address;
string city = address.City;
How to Solve or Handle NullReferenceException?
The preferred solution is usually to identify why the reference is null and either initialize it, reject the invalid value, or handle the absence explicitly. Catching the exception can prevent termination in specific situations, but it should not replace validation or correct object initialization.
Handle NullReferenceException Using Try-Catch
Well, the first is what we do to handle any exception. Its using C# try-catch. Use try catch statement around the code which has potential to the NullReferenceException. Then write your logic to work around the exception.
Program.cs
using System;
namespace CSharpExamples {
class Program {
static void Main(string[] args) {
string str = null;
try{
Console.WriteLine(str.Substring(5));
} catch(NullReferenceException err){
Console.WriteLine("Please check the string str.");
Console.WriteLine(err.Message);
}
Console.WriteLine("Continuing with other statments..");
}
}
}
Output
PS D:\workspace\csharp\HelloWorld> dotnet run
Please check the string str.
Object reference not set to an instance of an object.
Continuing with other statments..
Use this approach only when the application can recover meaningfully. In most application code, checking the reference before using it provides clearer control flow than deliberately allowing a null dereference and catching the resulting exception.
Check Whether the C# Reference Is Null
You can also check if the object is null, and apply the method or access property only if the reference is not null.
Program.cs
using System;
namespace CSharpExamples {
class Program {
static void Main(string[] args) {
string str = null;
if(str!=null){
Console.WriteLine(str.Substring(5));
} else {
Console.WriteLine("str is null.");
}
}
}
}
Output
PS D:\workspace\csharp\HelloWorld> dotnet run
str is null.
Modern C# also supports the is not null pattern, which makes the condition explicit:
if (str is not null)
{
Console.WriteLine(str.Length);
}
else
{
Console.WriteLine("str is null.");
}
Initialize the Object Before Accessing Its Members
When a reference is required for the program to continue, initialize it before calling its methods or reading its properties.
string str = "C# programming";
Console.WriteLine(str.Substring(3));
For class fields and properties, consider assigning a valid object in the constructor or using a property initializer.
class Customer
{
public Address Address { get; set; } = new Address();
}
class Address
{
public string City { get; set; } = string.Empty;
}
Use the Null-Conditional Operator for Optional Values
The null-conditional operators ?. and ?[] access a member or element only when the reference is not null. If the reference is null, the complete expression evaluates to null instead of throwing NullReferenceException.
string str = null;
int? length = str?.Length;
Console.WriteLine(length.HasValue ? length.Value : 0);
The operator can also be used in a nested property chain:
string city = customer?.Address?.City;
This prevents a null dereference, but it also allows city to be null. The calling code must decide how to handle that result.
Provide a Default with the Null-Coalescing Operator
The null-coalescing operator ?? returns its right-hand value when the left-hand expression is null. It is useful when the application has a sensible fallback.
string str = null;
string value = str ?? "Default text";
Console.WriteLine(value.Length);
The null-coalescing assignment operator ??= can initialize a variable only when it is currently null:
string str = null;
str ??= "Default text";
Console.WriteLine(str.Length);
Reject Required Null Arguments with ArgumentNullException
If a method cannot perform its work without a particular argument, validate that argument at the method boundary. Throwing ArgumentNullException identifies the invalid input more clearly than allowing a later NullReferenceException.
static void PrintUpperCase(string text)
{
ArgumentNullException.ThrowIfNull(text);
Console.WriteLine(text.ToUpper());
}
In projects targeting frameworks where ThrowIfNull() is unavailable, an explicit check can be used instead:
if (text is null)
{
throw new ArgumentNullException(nameof(text));
}
Debugging the Exact Null Reference in C#
The stack trace normally identifies the method and source-code line where the exception occurred. Start with that line, then inspect every reference that is dereferenced in the expression.
- Locate the first stack-trace entry that belongs to your application code.
- Set a breakpoint on the indicated line.
- Inspect each object used before a dot, indexer, or method call.
- Split complex expressions into separate local variables when necessary.
- Trace where the null value was assigned or returned.
- Decide whether the value should be initialized, validated, defaulted, or treated as optional.
For example, several references may be involved in the following statement:
Console.WriteLine(order.Customer.Address.City.ToUpper());
Check order, order.Customer, order.Customer.Address, and City. The exception message alone does not explain why the value became null, so tracing the value back to its source is an important part of the fix.
Prevent NullReferenceException with Nullable Reference Types
Nullable reference types let the compiler warn about code that may dereference null. In a nullable-enabled project, string represents a reference that should not be null, while string? represents a reference that may be null.
#nullable enable
string requiredName = "Alice";
string? optionalName = null;
if (optionalName is not null)
{
Console.WriteLine(optionalName.Length);
}
Nullable warnings are compile-time analysis rather than runtime enforcement. Values can still be null because of external data, older libraries, deserialization, reflection, or the null-forgiving operator. Runtime validation remains necessary at system boundaries.
C# NullReferenceException Fix Checklist
- Confirm which reference on the reported source-code line is null.
- Initialize required fields and properties before they are used.
- Validate method arguments and external input at entry points.
- Use
?.only when a missing value is valid and expected. - Use
??only when a real fallback value is appropriate. - Avoid empty catch blocks that hide the programming error.
- Enable nullable reference-type warnings in maintained C# projects.
- Add tests for missing input, unsuccessful lookups, and partially populated objects.
Frequently Asked Questions About C# NullReferenceException
What does “Object reference not set to an instance of an object” mean?
It means the program tried to use an instance member through a reference whose current value was null. No object instance was available for that method call or property access.
Should NullReferenceException always be handled with try-catch?
No. It is normally better to prevent the exception by initializing required objects, validating arguments, or explicitly handling optional values. Catch it only when the application has a meaningful recovery path.
Does the null-conditional operator completely fix NullReferenceException?
The ?. operator prevents a null dereference at the location where it is used, but the result may be null. Later code can still fail if it assumes that result contains a value.
Can a collection cause NullReferenceException even when the collection is initialized?
Yes. An initialized collection can contain null elements. Accessing a member through one of those elements can throw NullReferenceException.
What is the difference between NullReferenceException and ArgumentNullException?
NullReferenceException occurs when code dereferences a null value. ArgumentNullException is intentionally thrown by a method to report that a required argument was null. Validating the argument early usually produces a clearer error.
C# NullReferenceException Summary
In this C# Tutorial, we learned why NullReferenceException occurs, how to locate the null reference from a stack trace, and how to prevent it through initialization, validation, null checks, null-conditional access, default values, and nullable reference-type analysis.
TutorialKart.com