null List
This page was last reviewed on Sep 12, 2023.
Dot Net Perls
Null List. In C# programs, a List reference can be null. This is not the same as it being empty and having zero elements. We must often test for null lists.
Keyword info. The null literal in the C# language is a special-cased zero value for reference types. It is used often with the List type.
This program declares 3 List references and checks them against null. The program shows the difference between a List that is a field, such as a static List, and a List that is a local variable.
Also It causes a NullReferenceException when it tries to use a null list. This must be avoided.
Note The first List variable listA is initialized to a new empty List object. This variable does not have the value of null.
Note 2 The second List variable listB is initialized to the null literal. No memory is allocated on the managed heap in this assignment.
Finally The static field "listField" is located in one place in memory. If you assign it in different places, the same reference will be changed.
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); } }
False True True True
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object. at Program.Main....
List fields (and other reference types) are automatically treated as null references when they are loaded. You never need to initialize reference fields to null when you first encounter them.
Discussion. The book Refactoring by Martin Fowler contains a tutorial for replacing the null literal in a program with a "null object". This can simplify logic and reduce crashes.
Tip It makes sense to substitute a "dummy" object instance to stand in for cases where no data is available.
Summary. Lists that are fields in a class, either static or instance, are automatically initialized to null. Lists that are local variables are not initialized to null.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 12, 2023 (edit).
© 2007-2024 Sam Allen.