2.4.17 Null References With Lists

Null References With Lists

An object list can be missing, or an existing list can contain a missing Player reference. Distinguish those situations from an empty list.

Explore the idea
Distinguish three states

Use using System.Collections.Generic; at the top of the C# file, before its class definitions. Place the following statements inside an existing method. These examples use the established Player class and its public integer field NumberOfTurns.

A missing list, an empty list, and a null item
List<Player> missingPlayers = null;
List<Player> emptyPlayers = new List<Player>();
List<Player> players = new List<Player>();
players.Add(null);
Different states need different checks
State List exists? Count Can read a Player field?
missingPlayers No Cannot read Count No
emptyPlayers Yes 0 No item at index 0
players Yes 1 Index 0 contains null

Creating a list does not create Players. Adding null creates a current entry without creating a Player. Count includes that entry. These examples use the course’s Player reference model; a project with nullable reference analysis enabled may also warn about null assignments.

Skip missing objects while traversing
Visit only existing Players
Player jordan = new Player();
jordan.NumberOfTurns = 2;
players.Add(jordan);
int occupiedEntries = 0;

foreach (Player current in players)
{

    if (current != null)
    {
        current.NumberOfTurns = current.NumberOfTurns + 1;
        occupiedEntries = occupiedEntries + 1;
    }
}

Continue with players from the first example. The first pass receives null and skips the body of the if. The second receives Jordan and increases the turn count from 2 to 3. occupiedEntries is 1 even though Count is 2.

After traversal, index 0 contains null and index 1 reaches Jordan with NumberOfTurns 3. Count is 2 but occupiedEntries is 1.
One null entry and one Player after traversal
  • New
  • Changed
  • Removed
Check the correct thing
Guard a possibly missing list
int availableEntries = 0;

if (missingPlayers != null)
{
    availableEntries = missingPlayers.Count;
}

The null test protects access to the list itself. It does not prove that every entry reaches a Player. A separate item check protects a Player field read.

Predict and check