C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: This means that the string variable does not point to any object on the managed heap. It is equivalent to a null pointer.
Main: The string reference variable is assigned to the null literal. Next, the Length property is accessed on the string reference.
Info: The program compiles correctly, but always throws an execution. You cannot access an instance property like Length on a null reference.
C# program that raises NullReferenceException
using System;
class Program
{
static void Main()
{
string value = null;
if (value.Length == 0) // <-- Causes exception
{
Console.WriteLine(value); // <-- Never reached
}
}
}
Output
Unhandled Exception:
System.NullReferenceException: Object reference not set to an instance of an object.
at Program.Main() in C:\Users\...
However: If the parameter points to null, the compiler will not know this at compile-time. You must check for null at the method start.
Info: An array containing two elements is passed to the Test method. The Test method checks its parameter against the null literal.
Therefore: Test() will not throw when passed a null reference, as we see in the latter part of the Main method.
C# program that checks for null in method
using System;
class Program
{
static void Main()
{
// Create an array and use it in a method.
int[] array = new int[2];
array[0] = 1;
array[1] = 2;
Test(array);
// Use null reference in a method.
array = null;
Test(array); // <-- Won't crash
}
static void Test(int[] array)
{
if (array == null)
{
// You can throw an exception here, or deal with the argument.
return;
}
int rank = array.Rank;
Console.WriteLine(rank);
}
}
Also: In many programs you can use ArgumentNullException to notify the caller of errors.
But: For libraries and code APIs that will be used by others, more careful parameter checking to avoid NullReferenceExceptions is best.