C# Lists
Grow a collection with List<T> and add its values.
On this page
C# variables and loops.
- Grow a collection with List<T> and add its values.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
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.
Code example
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);
}
}4 344
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
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); }}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 |
Behind the scenes
How C# processes this code
C# compiles to code for the .NET runtime, which invokes the program entry point.
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.