List<T>: the resizable array
An array (Module 03) has a fixed length. List<T> is the collection you reach for when you do not know the size up front: it wraps an array and, when that array fills up, allocates a bigger one (double the size) and copies the items across. The <T> is a type argument — List<int> holds only ints, List<string> only strings — so the compiler checks every Add and you never cast on the way out.
var scores = new List<int> { 90, 72, 85 };
scores.Add(64);
scores.Insert(0, 100); // insert at index 0
scores.Remove(72); // removes the first 72
Console.WriteLine($"Count: {scores.Count}");
Console.WriteLine($"First: {scores[0]}, last: {scores[^1]}");
Console.WriteLine($"Has 85? {scores.Contains(85)}, index of 85: {scores.IndexOf(85)}");
scores.Sort();
Console.WriteLine(string.Join(", ", scores));
foreach (int s in scores)
{
if (s >= 85) Console.Write(s + " ");
}
Console.WriteLine();Count: 4
First: 100, last: 64
Has 85? True, index of 85: 2
64, 85, 90, 100
85 90 100Call scores.RemoveAt(0) after sorting and predict the new first element before you run it.
| Operation | Method | Cost |
|---|---|---|
| Read or write by index | list[i] | O(1) |
| Add to the end | Add(x) | O(1) on average (occasional resize) |
| Insert or remove in the middle | Insert(i, x), RemoveAt(i) | O(n) — every later item shifts |
| Search by value | Contains(x), IndexOf(x) | O(n) — a linear scan |
| Sort | Sort() | O(n log n) |
CS1503: adding the wrong type to a List<int>
var scores = new List<int> { 90, 85 };
scores.Add("100");Program.cs(2,12): error CS1503: Argument 1: cannot convert from 'string' to 'int'scores is a List<int>, so Add takes an int. A string that happens to contain digits is still a string — C# never converts it for you. This is the whole point of generics: the mistake is caught at compile time, not when some later code tries to do maths with it.
Pass an int, or parse the string explicitly if it really comes from text input.
var scores = new List<int> { 90, 85 };
scores.Add(100);
scores.Add(int.Parse("100"));Count is how many items you stored. Capacity is the size of the hidden array. If you know you are about to add 10,000 items, new List<int>(10_000) allocates once instead of resizing about fourteen times on the way up.