Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to capture null reference exception in C#?
A NullReferenceException occurs when you attempt to access a member (method, property, or field) of a null object reference. This is one of the most common runtime exceptions in C#.
What Causes NullReferenceException?
The exception is thrown when you try to access members of an object that has not been initialized or has been set to null −
string str = null; int length = str.Length; // Throws NullReferenceException
Using Null Checks
The most straightforward way to prevent NullReferenceException is to check for null before accessing object members −
using System;
class Program {
static void Main() {
int[] arr = new int[5] {1, 2, 3, 4, 5};
DisplayArrayInfo(arr);
arr = null;
DisplayArrayInfo(arr);
}
static void DisplayArrayInfo(int[] arr) {
if (arr == null) {
Console.WriteLine("Array is null");
return;
}
Console.WriteLine("Array rank: " + arr.Rank);
Console.WriteLine("Array length: " + arr.Length);
}
}
The output of the above code is −
Array rank: 1 Array length: 5 Array is null
Using Try-Catch Block
You can also use exception handling to catch and handle NullReferenceException −
using System;
class Program {
static void Main() {
string str = null;
try {
int length = str.Length;
Console.WriteLine("Length: " + length);
}
catch (NullReferenceException ex) {
Console.WriteLine("Caught NullReferenceException: " + ex.Message);
}
Console.WriteLine("Program continues executing");
}
}
The output of the above code is −
Caught NullReferenceException: Object reference not set to an instance of an object. Program continues executing
Using Null-Conditional Operator
C# provides the null-conditional operator (?.) which safely accesses members only if the object is not null −
using System;
class Person {
public string Name { get; set; }
public int Age { get; set; }
}
class Program {
static void Main() {
Person person = null;
// Safe access using null-conditional operator
string name = person?.Name;
int? age = person?.Age;
Console.WriteLine("Name: " + (name ?? "Not available"));
Console.WriteLine("Age: " + (age?.ToString() ?? "Not available"));
// Method chaining with null-conditional
int? nameLength = person?.Name?.Length;
Console.WriteLine("Name length: " + (nameLength?.ToString() ?? "Not available"));
}
}
The output of the above code is −
Name: Not available Age: Not available Name length: Not available
Best Practices
| Approach | When to Use | Advantage |
|---|---|---|
Null checks (if (obj == null)) |
When you need specific logic for null cases | Clear and explicit control flow |
Null-conditional operator (obj?.Member) |
For simple property access | Concise and readable code |
| Try-catch blocks | When null checks are impractical | Handles unexpected null scenarios |
Conclusion
Preventing NullReferenceException is crucial for robust C# applications. Use null checks for explicit control, null-conditional operators for concise code, and try-catch blocks as a safety net. Always validate object references before accessing their members to avoid runtime crashes.
