List<T> · C#
RemoveAt
Removes the element at a position and shifts the later elements left.
public void RemoveAt(int index)
Complexity
| Best case | O(1) for the last element |
|---|---|
| Worst case | O(n) for the first element |
| Extra space | O(1) |
Elements after index move one slot left, Count − index − 1 moves in total.
Tested example
var list = new List<int> { 5, 6, 7, 8 };
list.RemoveAt(0); // shifts 6, 7, 8 left
Assert.Equal([6, 7, 8], list);
list.RemoveAt(list.Count - 1); // removing the last element moves nothing
Assert.Equal([6, 7], list);
Parameters
- index
- 0 ≤ index < Count.
Behaviour
- Returns
- Nothing (read list[index] first if you need the value).
- Errors and preconditions
- ArgumentOutOfRangeException if index < 0 or index ≥ Count.
- Changes
- Count decreases by 1; the vacated last slot is cleared so the GC can reclaim what it referenced. Capacity is unchanged.
- Memory and invalidation
- Never shrinks the buffer. Invalidates enumerators.
See it step by step: the Dynamic arrays: capacity, resizing and amortized append lesson has an interactive 3D visualizer of the same mechanism.