2.4.12 Handling an Unsuccessful List Search

Handling an Unsuccessful List Search

The coach searches for a score that may not exist. A failed search is an expected outcome; check it before trying to read a list item.

Explore the idea
Separate search from indexed access

Use using System.Collections.Generic; at the top of the C# file, before its class definitions. Place the following statements inside an existing method.

Guard the search result
List<int> roundGoals = new List<int>();
roundGoals.Add(2);
roundGoals.Add(0);
roundGoals.Add(3);
int foundIndex = roundGoals.IndexOf(7);
bool found = false;
int selectedGoals = 0;

if (foundIndex >= 0)
{
    selectedGoals = roundGoals[foundIndex];
    found = true;
}

The bracket expression reads the item at a position. IndexOf returns -1 here, so the test is false and the body is skipped. found remains false; selectedGoals is only a placeholder.

Compare a hit with a miss
Same code, different search value
Target foundIndex Body executes? Result
7 -1 No found false; no item read
3 2 Yes selectedGoals 3; found true
0 1 Yes selectedGoals 0; found true

Searching an empty list also returns -1. A real score of 0 must not be confused with the placeholder; found tells you which case occurred.

Predict and check