How to capture null reference exception in C#?
Answers
Answer:
It handles errors generated from referencing a null object. The Null reference exception occurs when you are looking to access member fields or function types that points to null.
Let’s say we have the following null string −
string str = null;
Now you try to get the length of the null string, then it would cause an exception −
If(str.Length == null) {}
Above the exception will be thrown. Now let us seen how to prevent the null pointer exception to be thrown −
Example
using System;
class Program {
static void Main() {
int[] arr = new int[5] {1,2,3,4,5};
display(arr);
arr = null;
display(arr);
}
static void display(int[] arr) {
if (arr == null) {
return;
}
Console.WriteLine(arr.Rank);
}
}
Output
1
Explanation: