10
Lesson 10 of 35 ยท Foundations

Arrays & Collections

Arrays and collections allow you to store multiple values in a single variable. This lesson covers single-dimensional and multi-dimensional arrays, List<T>, Dictionary<K,V>, and the new C# 14 collection expression syntax.

Single-Dimensional Arrays

Declare an array with type[]. Access elements by zero-based index. The Length property returns the number of elements.

Array basics Arrays.cs
int[] scores = { 85, 92, 78, 96, 61 };

Console.WriteLine(scores[0]);        // 85
Console.WriteLine(scores.Length);    // 5

// Iterate
foreach (int s in scores)
    Console.Write(s + " ");

// Sort
Array.Sort(scores);
Console.WriteLine(string.Join(", ", scores)); // 61, 78, 85, 92, 96

C# 14 Collection Expressions

C# 14 introduces a unified [] syntax for creating arrays and collections, plus the spread operator .. to merge them.

Collection expressions CollectionExpr.cs
int[] evens = [2, 4, 6, 8];
int[] odds  = [1, 3, 5, 7];
int[] all   = [..evens, ..odds]; // spread

List names = ["Alice", "Bob", "Charlie"];

// Dictionary expression (C# 14)
Dictionary ages = new()
{
    ["Alice"] = 30,
    ["Bob"]   = 25,
};

List

List<T> is a resizable array. Use Add(), Remove(), Insert(), Contains(), and Count. The capacity doubles automatically as items are added.

List Lists.cs
var fruits = new List { "apple", "banana" };
fruits.Add("cherry");
fruits.Insert(0, "avocado"); // insert at index 0
fruits.Remove("banana");
Console.WriteLine(fruits.Count); // 3
Console.WriteLine(fruits[1]);    // apple

Dictionary

Dictionary<TKey,TValue> stores key-value pairs with O(1) average lookup. Keys must be unique and non-null.

Dictionary Dicts.cs
var capitals = new Dictionary
{
    ["France"]  = "Paris",
    ["Germany"] = "Berlin",
    ["Japan"]   = "Tokyo"
};

Console.WriteLine(capitals["France"]); // Paris

if (capitals.TryGetValue("Italy", out string? city))
    Console.WriteLine(city);
else
    Console.WriteLine("Not found");