10. Arrays & Lists
Most programs work with many values: users, orders, scores. C# stores them in collections. The two you will use every day are the array (fixed size) and the List<T> (grows and shrinks).
Arrays
An array holds a fixed number of values of one type. You choose the size when you create it, and it never changes. Elements are numbered from 0, and unset elements get the type's default value (0 for numbers).
["Ada", "Linus"]is a collection expression: create and fill in one step.^1counts from the end: the last element.1..4is a range: from index 1 up to, but not including, 4.
int[] scores = new int[3];
scores[0] = 90;
scores[1] = 75;
scores[2] = 82;
string[] names = ["Ada", "Linus", "Grace"];
Console.WriteLine($"First score: {scores[0]}");
Console.WriteLine($"Names: {names.Length}");
Console.WriteLine($"Last name: {names[^1]}");
int[] numbers = [10, 20, 30, 40, 50];
int[] middle = numbers[1..4];
Console.WriteLine($"Middle: {string.Join(", ", middle)}");
int[] empty = new int[2];
Console.WriteLine($"Default values: {empty[0]}, {empty[1]}");First score: 90 Names: 3 Last name: Grace Middle: 20, 30, 40 Default values: 0, 0
Reading scores[3] in a 3-element array throws an IndexOutOfRangeException. The valid indexes are 0 to Length - 1.
Multi-dimensional arrays
A rectangular array (int[,]) is a grid: every row has the same length. A jagged array (int[][]) is an array of arrays, so each row can have a different length. You will rarely need either in web APIs, but you should recognize them.
int[,] grid =
{
{ 1, 2, 3 },
{ 4, 5, 6 }
};
Console.WriteLine($"Rows: {grid.GetLength(0)}, Columns: {grid.GetLength(1)}");
Console.WriteLine($"Row 1, column 2: {grid[1, 2]}");
int[][] jagged =
[
[1],
[2, 3],
[4, 5, 6]
];
foreach (var row in jagged)
{
Console.WriteLine(string.Join(" ", row));
}Rows: 2, Columns: 3 Row 1, column 2: 6 1 2 3 4 5 6
Array methods
The Array class has static helpers for common jobs. IndexOf returns -1 when the value is missing. Sort, Reverse, and Clear change the array in place.
int[] numbers = [3, 7, 9, 2, 14, 6];
Console.WriteLine($"Index of 9: {Array.IndexOf(numbers, 9)}");
Console.WriteLine($"Index of 99: {Array.IndexOf(numbers, 99)}");
int[] copy = new int[3];
Array.Copy(numbers, copy, 3);
Console.WriteLine($"Copy: {string.Join(", ", copy)}");
Array.Sort(numbers);
Console.WriteLine($"Sorted: {string.Join(", ", numbers)}");
Array.Reverse(numbers);
Console.WriteLine($"Reversed: {string.Join(", ", numbers)}");
Array.Clear(numbers, 0, 2);
Console.WriteLine($"Cleared: {string.Join(", ", numbers)}");Index of 9: 2 Index of 99: -1 Copy: 3, 7, 9 Sorted: 2, 3, 6, 7, 9, 14 Reversed: 14, 9, 7, 6, 3, 2 Cleared: 0, 0, 7, 6, 3, 2
List<T>
A List<T> is like an array that resizes itself. The T is the type of the items: List<string>, List<int>. Use a list whenever you don't know the final size up front, which is most of the time.
Note the naming: arrays have Length, lists have Count.
List<string> todos = ["Learn C#"];
todos.Add("Build an API");
todos.AddRange(["Write tests", "Deploy"]);
todos.Insert(0, "Install .NET");
Console.WriteLine($"Count: {todos.Count}");
Console.WriteLine(string.Join(" | ", todos));
todos.Remove("Write tests");
todos.RemoveAt(todos.Count - 1);
Console.WriteLine(string.Join(" | ", todos));
Console.WriteLine($"Has 'Deploy'? {todos.Contains("Deploy")}");
Console.WriteLine($"Index of 'Build an API': {todos.IndexOf("Build an API")}");Count: 5 Install .NET | Learn C# | Build an API | Write tests | Deploy Install .NET | Learn C# | Build an API Has 'Deploy'? False Index of 'Build an API': 2
Removing items while looping
You cannot add or remove items from a list inside a foreach over that same list. C# throws an InvalidOperationException to protect you (the try/catch here just shows the error; exceptions come later).
Two fixes: loop backwards with for, so removing an item never shifts the ones you haven't visited yet, or use RemoveAll with a condition.
List<int> numbers = [1, 2, 3, 4, 5, 6];
try
{
foreach (var n in numbers)
{
if (n % 2 == 0)
numbers.Remove(n);
}
}
catch (InvalidOperationException)
{
Console.WriteLine("foreach failed: the list changed while looping");
}
for (int i = numbers.Count - 1; i >= 0; i--)
{
if (numbers[i] % 2 == 0)
numbers.RemoveAt(i);
}
Console.WriteLine($"Odd numbers: {string.Join(", ", numbers)}");
numbers.RemoveAll(n => n > 3);
Console.WriteLine($"After RemoveAll: {string.Join(", ", numbers)}");foreach failed: the list changed while looping Odd numbers: 1, 3, 5 After RemoveAll: 1, 3
Before you add a database, a List<T> is the perfect fake one. Return it from an endpoint and ASP.NET Core serializes it to a JSON array automatically:
List<string> todos = ["Learn C#", "Build an API"];
app.MapGet("/todos", () => todos);["Learn C#", "Build an API"]