Reading from a List
You read the items of a List<T> with the same square-bracket syntax as an array. This is called the list's indexer. Indexes are zero-based, so the first item is at index 0.
List<int> numbers = new List<int> {50, 60, 70};
Console.WriteLine(numbers[0]); // 50
int data = numbers[1];
Console.WriteLine(data); // 60
The result of numbers[1] is an ordinary int. You can store it in a variable, as above, or use it directly in an expression.
Valid indexes
A list with n items has valid indexes 0 through n - 1. The list above holds three items, so its last index is 2. Asking for numbers[3] throws an ArgumentOutOfRangeException. Methods such as get(0) belong to other languages; C# lists use brackets.
Visiting every item
When a list is long, a loop reads it for you. The index runs from 0 up to, but not including, Count:
List<string> fruits = new List<string> {"mango", "kiwi", "grapefruit"};
for (int i = 0; i < fruits.Count; i++) {
Console.WriteLine(i + ": " + fruits[i]);
}
0: mango
1: kiwi
2: grapefruit
If you only need the values, foreach (string f in fruits) is shorter and can't go past the end. Reading by index is the right tool when position matters, as in the exercise below.
Arrays and lists look alike
The syntax x[i] is the same for both, so code that only reads by index works with either. Only the size property differs: an array has Length, while a list has Count.
The exercise, step by step
The starter code builds a List<string> called fruits and a List<int> called ages. You add three print statements.
- The second fruit. The second item has index 1, so print
fruits[1], which is"kiwi". - The sum of the first three ages. Read
ages[0],ages[1]andages[2]and add them inside the call. The sum is evaluated before printing: 14 + 32 + 50 = 96. - The difference between the last and the first. There are four numbers, so the last is at index 3. Compute
ages[3] - ages[0], which is 21 - 14 = 7.
List<string> fruits = new List<string>(new[] {"mango", "kiwi", "grapefruit"});
List<int> ages = new List<int>(new[] {14, 32, 50, 21});
Console.WriteLine(fruits[1]);
Console.WriteLine(ages[0] + ages[1] + ages[2]);
Console.WriteLine(ages[3] - ages[0]);
The program prints:
kiwi
96
7
Common mistakes
- Off-by-one on "second". The second item is at index 1.
fruits[2]would givegrapefruit. - Reading past the end.
ages[4]on a four-item list throws an exception at run time. The code compiles, so the mistake only shows up when the line runs. - Using the wrong member names. Code ported from Java often uses
get(i)orsize(). In C#, uselist[i]and theCountproperty. - Text concatenation.
"Sum: " + ages[0] + ages[1]builds the textSum: 1432. Put the sum in parentheses if it is part of a message.
Why indexing starts at zero
An index is best thought of as an offset: how many steps you move from the start of the list. The first item is zero steps away, the second is one step away, and so on. That is why the first index is 0 and the last is Count - 1.
It also explains the off-by-one errors beginners meet. When you count items you start at 1, but when you number positions you start at 0, so the "third" item sits at index 2.
Reading never changes the list. Writing numbers[1] twice gives the same value both times, and nothing is removed from the list by looking at it.
Things to try
Predict each result before running it. For ages from the exercise, ages[3] - ages[2] is 21 - 50, which is -29. A list can also be used in a string, such as fruits[0].Length, which is 5, because an item that is a string supports everything a string does.
To check your understanding of the range, ask which indexes are valid for a list with five items. The answer is 0 to 4, so reading index 5 would throw an ArgumentOutOfRangeException.
Key takeaways
- A
List<T>is read withlist[index], exactly like an array. - Indexes start at 0 and end at
Countminus one. - An invalid index throws an
ArgumentOutOfRangeException.