skip to content

In C#, an array's length is fixed, so how does `List<T>` grow on `Add`, and what do `Count`, `Capacity` and `EnsureCapacity` control?

level: middleimportance: must knowfreq 70%

answer

  1. a hidden array behind the list
  2. Length is read-only on arrays
  3. empty until the first Add
  4. four, then double and copy

basics

~20 s

List<T> stores its items in an array: Count is how many it holds, Capacity is that array's length. An Add with no room allocates an array twice as long (four at first) and copies everything; a capacity hint avoids those copies.

solid answer

~40 s

An array's `Length` is fixed at creation, and assigning it fails with CS0200; `Array.Resize` allocates a new array, copies and rebinds only the variable passed by `ref`. `List<T>` does that for you: it keeps a backing `T[]` plus a count. `Count` is the number of elements, `Capacity` is the array's length. `new List<T>()` starts with an empty array; the first `Add` allocates 4 slots, and every `Add` that finds the array full allocates one twice as long, copies the elements with `Array.Copy` and drops the old array. `new List<T>(n)` allocates once, `EnsureCapacity(n)` grows to the larger of double the current capacity and `n` and returns the new capacity, and `TrimExcess` shrinks only when `Count` is under 90% of `Capacity`. `Clear` keeps the capacity.

code

csharp · 29 lines
csharp
var entities = new List<int>();
int lastCapacity = -1;
for (int i = 1; i <= 40; i++)
{
    entities.Add(i);
    if (entities.Capacity != lastCapacity)
    {
        Console.WriteLine($"Add #{i}: Count={entities.Count}, Capacity={entities.Capacity}");
        lastCapacity = entities.Capacity;
    }
}

var loaded = new List<int>(4) { 1, 2, 3, 4 };
Console.WriteLine(loaded.EnsureCapacity(5));   // 8: doubling beats the request
Console.WriteLine(loaded.EnsureCapacity(100)); // 100: the request beats doubling
loaded.Clear();
Console.WriteLine($"after Clear: Count={loaded.Count}, Capacity={loaded.Capacity}");
loaded.TrimExcess();
Console.WriteLine($"after TrimExcess: Capacity={loaded.Capacity}");

long Allocated(Action action)
{
    long before = GC.GetAllocatedBytesForCurrentThread();
    action();
    return GC.GetAllocatedBytesForCurrentThread() - before;
}
Allocated(() => new List<int>(1).Add(0)); // warm-up
Console.WriteLine(Allocated(() => { var l = new List<int>(); for (int i = 0; i < 100_000; i++) l.Add(i); }));
Console.WriteLine(Allocated(() => { var l = new List<int>(100_000); for (int i = 0; i < 100_000; i++) l.Add(i); }));

go deeper

for a junior

Know that an array cannot change length and that List<T> keeps an array inside it. Say what Count and Capacity each mean.

for a middle

Walk through growth: empty, then 4, then doubling, each step a new array plus a copy. Explain the constructor hint, EnsureCapacity's return value, TrimExcess's 90% rule and why Clear keeps the array.

for a senior

Find the repeated reallocations in a loader or a hot path from an allocation profile and fix them with a capacity taken from real data, not a guess. Reason about the abandoned arrays as garbage the collector must deal with.

for a principal

Capacity hints are a local fix; the decision worth owning is where bulk loads happen and whether their sizes are known up front, so the code can allocate once instead of growing.

## Arrays have a fixed length A C# array is created with its length and keeps it for life: `Length` is read-only, and `tiles.Length = 5` fails with **CS0200** ("Property or indexer 'Array.Length' cannot be assigned to -- it is read only"). An array has no `Add` method either. `Array.Resize(ref tiles, 5)` looks like an exception to that rule, but the reference source shows what it does: it allocates a **new array** of the requested length, copies the old elements across (truncating when shrinking) and assigns the new array to the variable you passed by `ref`. Any other variable that held the old array still points at it: ```csharp int[] tiles = { 1, 2, 3 }; int[] alias = tiles; Array.Resize(ref tiles, 5); // tiles.Length == 5, alias.Length == 3, ReferenceEquals(tiles, alias) == false ``` ## What a List<T> is made of `List<T>` is a growable wrapper around exactly that kind of array. It holds two fields that matter here: the **backing array** and a **size**. | Member | Meaning | |---|---| | `Count` | How many elements the list holds (the size) | | `Capacity` | The length of the backing array: how many elements fit before the next reallocation | | `new List<T>()` | Starts with a shared empty array, so `Capacity` is 0 | | `new List<T>(int capacity)` | Allocates the backing array at that length up front | `Count` is always less than or equal to `Capacity`. Reading `list[i]` checks `i` against `Count`, not `Capacity`, so the spare slots are invisible. ## How growth works When `Add` runs and `Count` equals `Capacity`, the list grows before storing the item. In the .NET 10 source (`List<T>.GetNewCapacity`) the steps are: 1. Compute a new capacity: **4** if the array is empty, otherwise **twice** the current length. 2. Clamp it to `Array.MaxLength`; if the caller needs more than the result (through `EnsureCapacity` or an insert of several items), use the requested number instead. 3. Allocate a new `T[]` of that length, copy the existing elements into it with `Array.Copy`, and replace the backing array. The old array becomes garbage. So a list filled one `Add` at a time has capacities 0, 4, 8, 16, 32, 64 and so on, and each step copies every element added so far. Each element is copied a bounded number of times on average, but each growth step is a fresh allocation, and the abandoned arrays add up. ## Measuring the cost Allocation is easiest to see with `GC.GetAllocatedBytesForCurrentThread()` around the work. On the .NET 10 runtime, adding 100,000 `int` values reports: - about **1,049,000 bytes** for `new List<int>()`, because the list allocated arrays of 4, 8, 16 and so on up to 131,072 elements on the way; - about **400,000 bytes** for `new List<int>(100_000)`, which is one array of exactly the right size. The time saved depends on the element type and the machine, so the mechanism, not a stopwatch reading, is the argument: every growth is an allocation plus a copy. ## Controlling capacity - **Constructor hint**: `new List<T>(expectedCount)` when you know or can estimate the final size. - **`EnsureCapacity(int)`**: grows the backing array to at least the requested size and returns the resulting capacity. It still applies the doubling rule, so a list with capacity 4 asked for 5 ends at 8, while asked for 100 it ends at exactly 100. It never shrinks. - **`Capacity` setter**: sets an exact length; a value below `Count` throws `ArgumentOutOfRangeException`. - **`TrimExcess()`**: sets `Capacity` to `Count` only when `Count` is below 90% of `Capacity`, so a list at 95 of 100 is left alone. - **`Clear()`**: sets `Count` to 0 but keeps the array; call `TrimExcess()` afterwards to release it. - **Bulk construction**: `new List<T>(collection)`, `AddRange` on an `ICollection<T>`, and a collection expression with a known element count size the array once. ## In the level editor A level file usually states how many entities it contains before it lists them. Reading that header and creating `new List<Entity>(header.EntityCount)`, or calling `EnsureCapacity` on an existing list, means the loader allocates one array instead of a dozen, which matters when levels are loaded while the editor is in use. After a large level is closed and the list cleared, `TrimExcess()` returns the big array to the garbage collector instead of keeping it for a level that may never come back.

  • Why does `list.EnsureCapacity(5)` on a `List<int>` with capacity 4 return 8 rather than 5?
    `EnsureCapacity` calls the same growth routine as `Add`: it computes double the current capacity and uses the requested number only when that is larger. Doubling 4 gives 8, which already covers 5, so the list allocates 8 slots. Asked for 100 from 8, doubling gives 16, so the request wins and the result is exactly 100.
  • A `List<T>` held a million entities and was cleared; why is its memory still in use, and how do you release it?
    `Clear` sets `Count` to 0 but keeps the backing array, so the list still owns room for a million elements (for element types that contain references it also clears the slots so the objects can be collected). Call `TrimExcess()` after `Clear`: with `Count` at 0, well under 90% of `Capacity`, it sets the capacity to 0 and drops the array. Setting `Capacity = 0` does the same.
  • When is passing a capacity to the `List<T>` constructor a mistake?
    When the estimate is far too large or the list usually stays small. `new List<T>(n)` allocates the whole array immediately, so a generous guess for many short-lived lists wastes memory on every one of them. Use a hint when the final count is known or tightly bounded, such as a count read from a file header.

  • A List<T> is a linked list, so Add never copies anything.
  • Capacity and Count are the same thing on a List<T>.
  • Array.Resize grows the existing array in place, so every reference sees the new length.
  • Clear releases the list's memory.
  • TrimExcess always sets Capacity to exactly Count.
  • EnsureCapacity(n) always allocates exactly n slots.