2.4.4 Defining Lists

Defining Lists

The coach needs a place to keep training scores even before any scores have been recorded. Declare a list variable and create its list instance as two distinct ideas.

Explore the idea
Create an empty list

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

Create a score list
List<int> roundGoals = new List<int>();
Separate a variable from its list
Declare first, then create
List<int> roundGoals;
roundGoals = new List<int>();

These two statements have the same final effect as the first example. A local variable declared without an assignment cannot be read until it has been assigned. Creating the list gives it zero items; it does not fill it with zeros.

Choose an element type

These examples use the established Player class and its public integer field NumberOfTurns.

Create an empty roster
List<Player> players = new List<Player>();

This creates one empty list and no Player objects. The list can later store Player references.

Predict and check