List<T> · C#
Insert
Inserts an element at a position, shifting the elements after it one slot to the right.
public void Insert(int index, T item)
Complexity
| Best case | O(1) at the end |
|---|---|
| Worst case | O(n) at the front |
| Extra space | O(1), plus O(n) if it triggers a resize |
Every element from index to Count − 1 is moved one slot (Array.Copy), so the cost is proportional to Count − index.
Tested example
var list = new List<string> { "a", "c", "d" };
list.Insert(1, "b"); // shifts "c" and "d" right
Assert.Equal(["a", "b", "c", "d"], list);
list.Insert(list.Count, "e"); // index == Count appends
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(10, "x"));
Parameters
- index
- 0 ≤ index ≤ Count; index == Count appends.
- item
- The element to insert.
Behaviour
- Returns
- Nothing.
- Errors and preconditions
- ArgumentOutOfRangeException if index < 0 or index > Count.
- Changes
- Count increases by 1; elements from index on move one slot right.
- Memory and invalidation
- May resize like Add. 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.