skip to content

In C#, why does List<T>.GetEnumerator return a public struct, and why does foreach over the same list allocate when it is typed as IEnumerable<T>?

level: middleimportance: should knowfreq 42%

answer

  1. static type decides which method
  2. public method vs explicit interface
  3. struct local vs heap copy
  4. IEnumerator<T> return type boxes

basics

~20 s

List<T>.Enumerator is a struct so foreach over a List<T> keeps the enumerator in a local with no heap allocation. Through IEnumerable<T>, GetEnumerator must return IEnumerator<T>, so the struct is boxed once per loop and each call becomes an interface call.

solid answer

~40 s

`List<T>` has a public `GetEnumerator()` returning the struct `List<T>.Enumerator`, plus an explicit `IEnumerable<T>.GetEnumerator()` returning `IEnumerator<T>`. `foreach` binds by the static type: on a `List<T>` it finds the public method, so the enumerator is a local, `MoveNext` and `Current` are direct calls the JIT can inline, and nothing is allocated. On an `IEnumerable<T>` only the interface method is visible; its return type is `IEnumerator<T>`, so the struct is boxed, one heap object per enumeration, and every call is an interface dispatch. The same happens in any method taking `IEnumerable<T>`, and in LINQ operators without a `List<T>` fast path. In .NET 10 an empty list returns a cached enumerator and the JIT can sometimes stack-allocate one, but the box is the rule.

code

csharp · 29 lines
csharp
var readings = new List<int> { 4, 8, 15, 16, 23, 42 };
IEnumerable<int> asSequence = readings;

for (int i = 0; i < 3; i++) { SumConcrete(readings); SumInterface(asSequence); } // warm up

long start = GC.GetAllocatedBytesForCurrentThread();
SumConcrete(readings);
long concrete = GC.GetAllocatedBytesForCurrentThread() - start;

start = GC.GetAllocatedBytesForCurrentThread();
SumInterface(asSequence);
long viaInterface = GC.GetAllocatedBytesForCurrentThread() - start;

Console.WriteLine($"foreach over List<int>:        {concrete} bytes");
Console.WriteLine($"foreach over IEnumerable<int>: {viaInterface} bytes");

static int SumConcrete(List<int> items)
{
    int sum = 0;
    foreach (int x in items) sum += x;   // List<int>.Enumerator lives in a local
    return sum;
}

static int SumInterface(IEnumerable<int> items)
{
    int sum = 0;
    foreach (int x in items) sum += x;   // IEnumerator<int>: the struct is boxed
    return sum;
}

go deeper

for a junior

Remember that the declared type of the variable matters: a List<T> variable gives foreach a struct enumerator, an IEnumerable<T> variable gives it an interface one.

for a middle

Explain the two GetEnumerator methods, why the interface's IEnumerator<T> return type forces a box, and that the cost is one allocation per loop, not per element.

for a senior

Spot the interface path in an allocation profile: IEnumerable<T> parameters, LINQ and exposed properties, and measure before rewriting, since .NET 10 can sometimes remove the box.

for a principal

Weigh exposing a public struct enumerator on a shared collection type: callers get allocation-free foreach, but also a mutable value type that misbehaves when stored or copied.

## Two `GetEnumerator` methods on one type `List<T>` declares two ways to get an enumerator: - `public List<T>.Enumerator GetEnumerator()`, returning **`List<T>.Enumerator`**, a public `struct` that implements `IEnumerator<T>`; - an **explicit** implementation of `IEnumerable<T>.GetEnumerator()`, returning `IEnumerator<T>` (and the non-generic `IEnumerable.GetEnumerator()` forwarding to it). `foreach` binds by the **static type** of the expression it is given. The pattern lookup looks for a public instance `GetEnumerator()` first, so: - when the expression's type is `List<T>`, the loop gets the struct. It lives in a local variable, `MoveNext` and `Current` are direct, non-virtual calls the JIT can inline, and the generated `finally` calls `Dispose` through a constrained call without boxing. **No heap allocation.** - when the expression's type is `IEnumerable<T>`, `IReadOnlyList<T>`, `ICollection<T>` or any other interface, only the interface method is visible. It returns `IEnumerator<T>`, so the struct is **boxed**: copied into a new heap object. Every `MoveNext` and `Current` call is then an interface dispatch. The list and its elements are identical in both loops; only the compile-time type of the variable changed. ## What the box costs | | `foreach` over `List<T>` | `foreach` over `IEnumerable<T>` | |---|---|---| | enumerator | `List<T>.Enumerator` in a local | boxed copy on the heap | | allocations per loop | none | one object per enumeration | | `MoveNext` / `Current` | direct calls, inlinable | interface calls | | `Dispose` | constrained call, no box | interface call on the box | The cost is **one allocation per enumeration, not per element**: in the example it is 40 bytes for a `List<int>` on .NET 10 (64-bit), and the number did not drop after the method had been called a few hundred thousand times. One small object rarely matters; a loop that enumerates small collections through an interface thousands of times per frame or per request turns into steady garbage-collector work, which is where the difference shows up in an allocation profile. Two .NET 10 details soften this without changing the rule: 1. `List<T>`'s interface `GetEnumerator()` returns a shared, cached empty enumerator when the list has no elements, so enumerating an **empty** list through `IEnumerable<T>` allocates nothing. 2. The .NET 10 JIT's array enumeration de-abstraction and conditional escape analysis can stack-allocate enumerators **in certain scenarios** where it can see the concrete type. It is an optimization, not a guarantee; measure with `GC.GetAllocatedBytesForCurrentThread()` or a benchmark's memory diagnostics before relying on it. ## Where the interface path hides - A method parameter typed `IEnumerable<T>`, `IReadOnlyCollection<T>` or `IList<T>` that loops over its argument. - LINQ: every operator receives its source as `IEnumerable<T>`. Some operators have fast paths for arrays and `List<T>`, but otherwise enumerating the source goes through the interface enumerator, on top of the operator's own iterator object. - A generic method constrained `where TSource : IEnumerable<T>`: the constraint does not help, because the interface's `GetEnumerator()` is declared to return `IEnumerator<T>`, so the struct is boxed on return. - A property that exposes an internal `List<T>` as `IEnumerable<T>` to callers in the same hot path. When a hot internal loop needs the struct, take the concrete collection type, or index it with a `for` loop. ## Designing a struct enumerator for your own type A fixed-capacity `RingBuffer<T>` in a telemetry agent can copy the `List<T>` design: 1. Declare `public Enumerator GetEnumerator()` returning a public nested `struct Enumerator` with `MoveNext()` and `Current`. 2. Implement `IEnumerable<T>` as well, explicitly: `IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator();`. LINQ callers still work; they pay the box, the `foreach` callers do not. 3. Let the struct implement `IEnumerator<T>` so the explicit method can return it, with an empty `Dispose()` when there is nothing to release. 4. Keep its fields few: the struct is copied whenever it is assigned or passed by value, and it is **mutable**, so a copy taken mid-loop does not advance with the original. The trade-off is that last point: a struct enumerator saves an allocation and gains copy semantics, which callers who store or pass it around can trip over. ## Telling which enumerator a loop got - In an allocation profile, the interface path shows up as instances of the boxed struct type, `List<T>.Enumerator` (each tool spells nested generic type names its own way), allocated from the method that loops. A struct enumerator used directly never appears there. - In the IL, the direct path keeps a local of type `List<T>.Enumerator` and calls its `MoveNext()` with `call`; the interface path keeps an `IEnumerator<T>` local and calls `MoveNext()` with `callvirt` on the interface. - In the source, the quickest check is the declared type of the expression after `in`: hover over it in the editor, and if it is an interface, the loop takes the interface path.

  • Does constraining a C# generic method with where TSource : IEnumerable<T> avoid boxing List<T>.Enumerator?
    No. The method can only call `IEnumerable<T>.GetEnumerator()`, and that member is declared to return `IEnumerator<T>`, so the struct is boxed on the way out whatever `TSource` is. Avoiding the box needs the caller to bind to the public `GetEnumerator()`: take `List<T>` itself, or loop with an index.
  • In .NET 10, does foreach over an empty List<T> held as IEnumerable<T> allocate?
    No. `List<T>`'s explicit `IEnumerable<T>.GetEnumerator()` returns a shared, cached empty enumerator when `Count` is zero and boxes `List<T>.Enumerator` only for a non-empty list. A non-empty list still allocates one enumerator object per loop, unless the .NET 10 JIT manages to stack-allocate it in that particular call site.

  • foreach over IEnumerable<T> allocates once for every element it visits.
  • Constraining a generic parameter to IEnumerable<T> stops the enumerator being boxed.
  • List<T>.Enumerator is a class, so foreach always allocates it.
  • The runtime type of the list decides which GetEnumerator foreach calls.
  • A struct enumerator is safe to copy because it holds only a reference.