C# · Dynamic array · container
List<T>
A growable array: contiguous storage with spare capacity, O(1) indexing and amortized O(1) appends at the end.
using System.Collections.Generic; // implicit in SDK-style projects public class List<T> : IList<T>, IReadOnlyList<T>
.NET 10 (all operations shown exist since .NET Framework 2.0 except where noted)
Operations
| Operation | Time | Worst case | Changes the collection |
|---|---|---|---|
| Add | O(1) | O(n) when the buffer is full | Yes |
| Insert | O(n) at the front | O(n) at the front | Yes |
| RemoveAt | O(n) for the first element | O(n) for the first element | Yes |
| Indexer this[int] | O(1) | O(1) | Yes |
| Contains / IndexOf | O(n) | O(n) | No |
| Sort | O(n log n) | O(n log n) | Yes |
"Time" shows the amortized, expected or average bound when one applies; open an operation for the full profile and its assumptions.
How it works
- Representation
- A private T[] buffer plus a count. When the buffer is full, Add allocates a larger array (the current implementation doubles, starting at 4) and copies every element across.
- Ordering
- Insertion order; elements stay where you put them until you insert, remove or sort.
- Duplicates
- Allowed.
- Mutability
- Mutable. Changing the list while enumerating it with foreach throws InvalidOperationException on the next MoveNext.
- Memory and ownership
- Capacity ≥ Count; the spare slots are allocated but unused. Value types are stored inline in the array; reference types store references. Capacity never shrinks automatically (TrimExcess or setting Capacity does).
- Equality and comparison
- Contains, IndexOf and Remove use EqualityComparer<T>.Default (IEquatable<T> if implemented, else Equals). Sort uses Comparer<T>.Default or the comparison you pass.
Pitfalls
- Insert(0, x) and RemoveAt(0) shift every element: O(n). Use Queue<T> or LinkedList<T> when you work at the front.
- List<T>.Sort is an introspective sort and is not stable. Use LINQ OrderBy when equal elements must keep their order.
- Count, not Capacity, bounds the indexer: list[Count] throws even if the buffer has room.
- Removing inside a foreach throws. Iterate backwards with a for loop, or use RemoveAll(predicate).
Alternatives
- T[] for a fixed size
- Queue<T> for FIFO
- LinkedList<T> for O(1) insertion at a known node
- ImmutableList<T> for persistent snapshots
In other languages
- Python: list
- Java: ArrayList<E>
- C++: std::vector<T>