C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Also: It causes a NullReferenceException when it tries to use a null list. This must be avoided.
NullList A: The first List variable listA is initialized to a new empty List object. This variable does not have the value of null.
List B: The second List variable listB is initialized to the null literal. No memory is allocated on the managed heap in this assignment.
List field: This field is located in one place in the entire program's memory. If you assign it in different places, the same reference will be changed.
C# program that uses null Lists
using System;
using System.Collections.Generic;
class Program
{
//
// Field type List.
//
static List<int> _listField;
static void Main()
{
//
// Shows an empty List, not a null List.
//
List<string> listA = new List<string>();
Console.WriteLine(listA == null);
//
// A null List reference.
//
List<string> listB = null;
Console.WriteLine(listB == null);
//
// Calling an instance method on a null List causes a crash.
//
// listB.Add("cat");
//
// Static Lists and field Lists are automatically null.
//
Console.WriteLine(_listField == null);
Console.WriteLine(default(List<bool>) == null);
}
}
Output
False
True
True
True
Exception caused by null Lists
Unhandled Exception: System.NullReferenceException:
Object reference not set to an instance of an object.
at Program.Main....
And: You cannot call an instance method on a null List. The default value expression returns null for the List constructed type.
Default