List<T> · C#
Indexer this[int]
Reads or overwrites the element at a position by index arithmetic.
public T this[int index] { get; set; }Complexity
| Best case | O(1) |
|---|---|
| Worst case | O(1) |
| Extra space | O(1) |
The element lives at a fixed offset in the buffer: start + index × element size.
Tested example
var list = new List<int> { 1, 2, 3 };
list[1] = 20;
Assert.Equal(20, list[1]);
Assert.Throws<ArgumentOutOfRangeException>(() => list[3]); // Count, not Capacity, is the limit
Parameters
- index
- 0 ≤ index < Count.
Behaviour
- Returns
- The element (get).
- Errors and preconditions
- ArgumentOutOfRangeException if index < 0 or index ≥ Count, even when index < Capacity.
- Changes
- Get: nothing. Set: replaces one element (and invalidates enumerators).
- Memory and invalidation
- No allocation.