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 caseO(1)
Worst caseO(1)
Extra spaceO(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
Runs in the test suite on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples.Tests/Collections/ListExamples.cs

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.