C# Lists
Grow a collection with List<T> and add its values.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
var scores = new List<int> { 82, 91, 76 };
scores.Add(95);
int total = 0;
foreach (int score in scores) {
total += score;
}
Console.WriteLine(scores.Count);
Console.WriteLine(total);
}
}Output
4 344
Explanation
List<T> is a resizable array from System.Collections.Generic. The T is the element type, so List<int> holds only integers, and the compiler rejects anything else.
Add appends to the end, Count reports how many items it holds, and foreach visits each item in order. The collection initializer { 82, 91, 76 } fills the list when it is created.
Explore the dry run
Guided walkthroughReady
1
using System;2
using System.Collections.Generic;3
4
class Program {5
static void Main() {6
var scores = new List<int> { 82, 91, 76 };7
scores.Add(95);8
int total = 0;9
foreach (int score in scores) {10
total += score;11
}12
Console.WriteLine(scores.Count);13
Console.WriteLine(total);14
}15
}Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Create a list holding three integers. | scores = [82, 91, 76] | — | |
| Append a fourth value. | scores = [82, 91, 76, 95] | — | |
| Each pass adds one score; the total ends at 344. | total = 344 | — | |
| Count is the number of items. | total = 344 | 4 | |
| Print the sum. | total = 344 | 4 344 |
Cost and common mistakes
Add is amortized O(1); the loop is O(n) time with O(1) extra space.
- Changing a List inside a foreach over the same list throws InvalidOperationException.
- Indexing past Count - 1 throws ArgumentOutOfRangeException.
Try it yourself
Print the largest score without using LINQ.
Reveal answer and reasoning
Keep int max = scores[0] and replace it inside the loop whenever score > max. It prints 95.