C# · Course navigation

C# Lists

Grow a collection with List<T> and add its values.

On this page
Before you start

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

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

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1using System;
2using System.Collections.Generic;
3
4class 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
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput 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.

Further reading