List<T> · C#
Add
Appends an element at the end, growing the buffer first if it is full.
public void Add(T item)
Complexity
| Best case | O(1) |
|---|---|
| Amortized | O(1) |
| Worst case | O(n) when the buffer is full |
| Extra space | O(1) amortized; a resize temporarily holds both buffers (O(n)) |
With room, Add writes one slot. When full, the capacity doubles and all n elements are copied. Because the capacity doubles, n appends copy fewer than 2n elements in total, so each append costs O(1) on average over the sequence.
Tested example
var list = new List<int>(capacity: 2);
list.Add(10);
list.Add(20);
list.Add(30); // full: grows the buffer, copies 2 elements
Assert.Equal(3, list.Count);
Assert.True(list.Capacity >= 3);
Parameters
- item
- The element to append (null is allowed for reference types).
Behaviour
- Returns
- Nothing.
- Errors and preconditions
- None in normal use (OutOfMemoryException if the buffer cannot grow).
- Changes
- Count increases by 1; may replace the internal buffer.
- Memory and invalidation
- A resize allocates a new array and the old one becomes garbage. Any enumerator in progress is invalidated (it throws on the next MoveNext).
See it step by step: the Dynamic arrays: capacity, resizing and amortized append lesson has an interactive 3D visualizer of the same mechanism.