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
C# NullReferenceException
A NullReferenceException is one of the most common runtime exceptions in C#. It occurs when you try to access a member (property, method, or field) of an object reference that is null.
When NullReferenceException Occurs
This exception is thrown when −
-
You call a method on a null reference
-
You access or modify a property of a null reference
-
You get the length of a null array or string
-
You index into a null array
Example: Accessing Null String
using System;
class Demo {
static void Main() {
string str = null;
if (str.Length > 0) {
Console.WriteLine(str);
}
}
}
The output of the above code is −
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object at Demo.Main()
Example: Accessing Null Array
using System;
class Demo {
static void Main() {
int[] numbers = null;
Console.WriteLine("Array length: " + numbers.Length);
}
}
The output of the above code is −
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object at Demo.Main()
How to Prevent NullReferenceException
Using Null Checks
using System;
class Demo {
static void Main() {
string str = null;
if (str != null && str.Length > 0) {
Console.WriteLine(str);
} else {
Console.WriteLine("String is null or empty");
}
int[] numbers = null;
if (numbers != null) {
Console.WriteLine("Array length: " + numbers.Length);
} else {
Console.WriteLine("Array is null");
}
}
}
The output of the above code is −
String is null or empty Array is null
Using Null-Conditional Operator (?.) - C# 6.0+
using System;
class Person {
public string Name { get; set; }
}
class Demo {
static void Main() {
Person person = null;
// Safe access using null-conditional operator
string name = person?.Name ?? "Unknown";
Console.WriteLine("Name: " + name);
// Safe method call
int? length = person?.Name?.Length;
Console.WriteLine("Name length: " + (length?.ToString() ?? "N/A"));
}
}
The output of the above code is −
Name: Unknown Name length: N/A
Common Scenarios and Prevention
| Scenario | Problem | Solution |
|---|---|---|
| Uninitialized reference | string str; str.Length |
Check str != null before access |
| Method returns null | GetObject().Method() |
Store result and check before use |
| Array element is null | array[0].Property |
Check array[0] != null
|
| Event handler is null | SomeEvent() |
Use SomeEvent?.Invoke()
|
Conclusion
NullReferenceException occurs when attempting to access members of a null reference. Prevent it by checking for null before accessing object members, using the null-conditional operator (?.), or ensuring proper object initialization. Always validate object references before use to avoid runtime exceptions.
