Skip to content
Codewilds

Lesson 14 of 34 · Arrays & Lists

C# List<T>: Resizable Lists

easy10 XP3 min read

Arrays have one big limitation: their size is fixed. A shopping cart, a quest log or a party of heroes grows and shrinks while the program runs. For that, C# has List<T> — the collection you will use more than any other.

Creating a list

List<T> is a generic type: the T in angle brackets says what the list holds.

List<string> party = new List<string>();   // empty list of strings
var loot = new List<int> { 10, 25, 5 };    // with an initializer
List<string> spells = ["fire", "ice"];     // collection expression

The List<T> class lives in System.Collections.Generic, which every C# program in this course can already use.

Adding, reading and removing

var party = new List<string> { "Aria", "Bo" };
party.Add("Cy");                 // Aria, Bo, Cy
party.Insert(0, "Dax");          // Dax, Aria, Bo, Cy
Console.WriteLine(party[1]);     // Aria — indexing works like arrays
Console.WriteLine(party.Count);  // 4 — Count, not Length
party.Remove("Bo");              // removes the first "Bo" (returns true if found)
party.RemoveAt(0);               // removes by index → Aria, Cy
party.AddRange(["Eve", "Fin"]);  // Aria, Cy, Eve, Fin

Searching and sorting

var numbers = new List<int> { 5, 3, 8, 3 };
numbers.Contains(8);      // true
numbers.IndexOf(3);       // 1 (first match, -1 if missing)
numbers.Sort();           // 3, 3, 5, 8
numbers.Reverse();        // 8, 5, 3, 3
int smallest = numbers.Min();   // 3
numbers.Clear();          // empty

Looping over a list

foreach and for work exactly like with arrays:

var prices = new List<decimal> { 4.5m, 10m, 2.25m };
decimal total = 0;
foreach (decimal p in prices)
{
    total += p;
}

Do not change a list inside its foreach

While a foreach loop is walking through a list, the list must not change. Adding or removing items inside the loop throws an InvalidOperationException ("Collection was modified"):

foreach (string name in party)
{
    if (name.StartsWith("A"))
    {
        party.Remove(name);   // 💥 InvalidOperationException
    }
}

Two safe alternatives: let the list do it with RemoveAll, which takes a condition written as a lambda (x => ... reads as "for each item x, check ..."), or loop backwards with an index so removals do not shift the elements you have not visited yet:

party.RemoveAll(name => name.StartsWith("A"));

for (int i = party.Count - 1; i >= 0; i--)
{
    if (party[i].StartsWith("A")) party.RemoveAt(i);
}

Lists are references too

Like arrays, lists are reference types. A method that receives a list can add and remove items, and the caller sees the changes. That is useful — AddUnique below relies on it — but when a method is supposed to produce a new list, create one with new List<T>() instead of modifying the input.

Common mistakes

  • list.Length — lists use Count.
  • list[list.Count] — the last index is Count - 1.
  • Removing items inside foreach — use RemoveAll or a backwards for.

Assignment

Complete four methods in Program:

  1. Evens(numbers) returns a new list with only the even numbers, in their original order.
  2. AddUnique(items, item) adds item to items only if it is not already there. Return true if it was added, false otherwise.
  3. RemoveShortWords(words, minLength) removes every word shorter than minLength from words in place and returns how many words were removed.
  4. Merge(a, b) returns a new list containing every number from both lists exactly once, sorted ascending: Merge([3, 1], [2, 3]) is [1, 2, 3].

Premium lesson

Unlock the full Learn C# course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Lists that grow in other languages

Need a quick reminder? The C# cheat sheet has every topic of Learn C# on one page.

Lesson last updated on .

Write code ↓
C#+10 XP

Lesson 14 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn C# course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.