C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Here: The example demonstrates the difference between an empty array of zero elements and a null array reference.
Locals: Local variables in the .NET Framework are stored in a separate part of the metadata. They do not implicitly initialize to null.
Fields: Fields that are of a reference type such as an array type like int[] are implicitly assigned to null.
Finally: The example reports that the default(int[]) expression is equal to null. It writes to the screen with Console.WriteLine.
ConsoleC# program that uses null array references
using System;
class Program
{
static int[] _arrayField1 = new int[0]; // Empty array
static int[] _arrayField2; // Null
static void Main()
{
//
// Shows an empty array is not a null array.
//
int[] array1 = new int[0];
Console.WriteLine(array1 == null);
//
// Shows how to initialize a null array.
//
int[] array2 = null;
Console.WriteLine(array2 == null);
//
// Static and instance field arrays are automatically null.
//
Console.WriteLine(_arrayField1 == null); // Empty array
Console.WriteLine(_arrayField2 == null); // Null
//
// Default expression for arrays evaluates to null.
//
Console.WriteLine(default(int[]) == null);
}
}
Output
False
True
False
True
True
Tip: It is never worthwhile to loop through an array you allocate and assign all its elements to null. This occurs implicitly in the CLR.
Array: The program allocates a string array of 3 elements. These elements are initialized to null in the runtime and you can test them against null.
Warning: Using an instance member on one of the elements will result in a NullReferenceException.
ArrayNullReferenceExceptionC# program that tests default values
using System;
class Program
{
static void Main()
{
//
// Value for all reference elements in new array is null.
//
string[] array = new string[3];
Console.WriteLine(array[0] == null);
Console.WriteLine(array[1] == null);
Console.WriteLine(array[2] == null);
}
}
Output
True
True
True
Info: The memory is never uninitialized or garbage as you would encounter in C or C++. This helps promote program reliability.