2.4.6 Type Safety in Generic Lists

Type Safety in Generic Lists

The coach keeps whole-number scores separate from Player references. The type inside a list’s angle brackets tells C# which kinds of item the list accepts.

Explore the idea
Use one declared element type

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

Integer list
List<int> roundGoals = new List<int>();
roundGoals.Add(2);

Add appends one item; the next activity explains it in detail. Here the important point is that 2 is an integer.

Diagnose a type mismatch

This example is intentionally invalid.

Intentional compile error
List<int> roundGoals = new List<int>();
roundGoals.Add("two");

The compiler rejects the Add call because "two" is a string, not an int. The program does not start and then fail on that line. Replace it with roundGoals.Add(2);.

These examples use the established Player class and its public integer field NumberOfTurns. A List<Player> accepts a Player reference, not an integer turn count. A null reference is a separate case addressed later; element type safety alone does not guarantee a usable object.

Predict and check