List

Intro

List<T> is the default dynamic array in .NET. Use it when you need ordered data, fast index access, and efficient appends.

Deeper Explanation

List<T> stores items in a contiguous array, so indexing by position is O(1) and iterating is cache friendly.
When Count grows past Capacity, the internal array is reallocated and copied to a larger buffer.

When Count exceeds Capacity, List<T> allocates a new internal array with double the current capacity (power-of-two growth), copies all elements, and releases the old buffer. The doubling strategy ensures any sequence of n appends costs O(n) total — amortized O(1) per append — even though individual resize events are O(n). The pre-sizing constructor new List<T>(capacity) eliminates resizes for known-size collections, which matters in hot paths where repeated allocation and GC pressure are measurable. Prefer Capacity pre-sizing over post-construction TrimExcess when the final size is known upfront.

Structure

graph LR
    I0[index zero ann] --> I1[index one bob] --> I2[index two chris]

Example

var users = new List<string>(capacity: 4) { "Ann", "Bob" };
users.Add("Chris");
users.Remove("Bob");

// O(1) index access
Console.WriteLine(users[0]);

Pitfalls

Tradeoffs

Questions

List class — API reference with remarks on capacity, sorting, and searching. Supplemental API remarks for List — additional guidance on performance characteristics and common patterns.
  • When to use generic collections — explains why List<T> replaces ArrayList and when to prefer other collection types.
  • List implementation in dotnet runtime — source code showing the internal array, capacity doubling, and resize logic.

  • Whats next

    Parent
    02 Computer Science

    Pages