Lesson 8 · ~12 min · ← Lesson 7

Collections: arrays, List, Dictionary

Almost every program is "hold a bunch of things, then do something with them." C#'s three workhorses cover 95% of that: the array (fixed size, fastest), the List<T> (grows), and the Dictionary (find by key).

Array: a row of boxes, size fixed at birth

int[] scores = new int[3];       // exactly 3 slots, decided here
scores[0] = 72;
scores[1] = 95;
scores[2] = 88;

int total = 0;
for (int i = 0; i < scores.Length; i++)   // arrays use .Length
{
    total += scores[i];
}
Console.WriteLine("total: " + total + " count: " + scores.Length);

Indexes start at 0, so the last slot is Length - 1 — go past it and you get IndexOutOfRangeException at runtime. Shorter form when you know the values: int[] scores = { 72, 95, 88 };

List<T>: same row of boxes, grows on demand

var names = new List();
names.Add("Ada");
names.Add("Grace");
names.Add("Linus");

Console.WriteLine(names.Count);          // List uses .Count, not .Length

names.RemoveAt(0);                       // remove by index — array can't do this
Console.WriteLine(string.Join(", ", names));

The <string> is a type argument: this list holds strings and the compiler enforces it. Add, Remove, Contains, IndexOf, Sort, Reverse — the everyday toolbox. Note .Count here vs .Length for arrays; mixing them up is harmless, the error message will remind you (CS1061).

Dictionary: no indexes — look things up by KEY

var ages = new Dictionary();   // keys are strings, values are ints
ages["Ada"] = 36;                           // add or update by key
ages["Grace"] = 45;

Console.WriteLine(ages["Ada"] + ages["Grace"]);

foreach (string k in ages.Keys)             // iterate the keys
{
    Console.WriteLine(k + " -> " + ages[k]);
}

if (ages.TryGetValue("Linus", out int age)) // the safe lookup
{
    Console.WriteLine(age);
}
else
{
    Console.WriteLine("Linus not found");
}

One trap: reading a missing key with ages["Linus"] throws KeyNotFoundException — that's why TryGetValue exists. It's the dictionary's version of int.TryParse: try the lookup, branch on success.

foreach works over all three

int[] arr = { 72, 95, 88 };
var list = new List { 1, 2, 3 };

foreach (int x in arr)  Console.Write(x + " ");
foreach (int x in list) Console.Write(x + " ");

(The dictionary needs foreach over .Keys/.Values in this engine — pairs come back as KeyValuePair which is on the roadmap.)

Which one, when?

NeedUseWhy
Fixed set of slots, index math, performanceT[]Smallest, fastest, no resize
"A list of things" that grows/shrinksList<T>The default choice in modern C#
Look up by name/id, not positionDictionary<K,V>Instant key lookup
Just iterate onceany + foreachNo index needed at all

Practice this now