Arrays and List
Arrays and List<T>
Arrays
An array has a fixed length and stores elements of one type. Indexes start at 0.
int[] numbers = { 1, 2, 3, 4, 5 };
Console.WriteLine(numbers[0]); // 1
Console.WriteLine(numbers.Length); // 5
int[] zeros = new int[3]; // { 0, 0, 0 }
Going out of bounds (numbers[5]) throws an IndexOutOfRangeException.
List<T>
When the number of elements changes, use List<T>:
var names = new List<string>();
names.Add("Ana");
names.Add("Boris");
names.Remove("Ana");
Console.WriteLine(names.Count); // 1
You need using System.Collections.Generic; (implicit in new projects).
Which one to pick?
| Need | Choice |
|---|---|
| Fixed number of items | array |
| Adding and removing | List<T> |
| Fast access by index | both |
Practice
Solve "Sum of an array": read n, then n numbers, and add them up. Try it once with an array and once with a List<int>.