In C#, what does a type need for foreach to compile over it, and what does the compiler turn the loop into?
answer
- a method name, not an interface
- GetEnumerator, then two members
- bool MoveNext and a readable Current
- while loop wrapped in try/finally
basics
~20 sforeach needs a GetEnumerator() method whose return type has a public bool MoveNext() and a readable Current; no interface is required. The compiler lowers the loop to a while over MoveNext inside a try/finally that disposes a disposable enumerator.
solid answer
~40 s`foreach` is pattern-based. The compiler looks for a public instance `GetEnumerator()` on the collection's type, then for `IEnumerable<T>` or `IEnumerable`, and since C# 9 for an extension method named `GetEnumerator`. The returned type needs a public `bool MoveNext()` and a readable `Current`, whose type is the element type. The loop becomes `var e = c.GetEnumerator(); try { while (e.MoveNext()) { var x = e.Current; ... } } finally { /* dispose e */ }`, and the `finally` is emitted only when the enumerator is disposable or, for a non-sealed class or an interface, might be. Arrays, `string`, `Span<T>` and `ReadOnlySpan<T>` skip the enumerator and compile to an indexed `for` loop. A type with no `GetEnumerator` by any route fails with CS1579.
code
csharp · 29 linesvar buffer = new RingBuffer<int>(3);
foreach (var n in new[] { 1, 2, 3, 4, 5 }) buffer.Add(n);
foreach (int reading in buffer)
Console.Write($"{reading} "); // 3 4 5
Console.WriteLine();
public sealed class RingBuffer<T>(int capacity)
{
private readonly T[] _items = new T[capacity];
private int _start, _count;
public void Add(T item)
{
_items[(_start + _count) % _items.Length] = item;
if (_count < _items.Length) _count++;
else _start = (_start + 1) % _items.Length;
}
// No interface: foreach binds to this method by name.
public Enumerator GetEnumerator() => new(this);
public struct Enumerator(RingBuffer<T> owner)
{
private int _offset = -1;
public bool MoveNext() => ++_offset < owner._count;
public T Current => owner._items[(owner._start + _offset) % owner._items.Length];
}
}go deeper
Recall the two-step shape: GetEnumerator, then MoveNext and Current in a loop. Say plainly that no interface is required, only those members.
Explain the lookup order (public method, then the interfaces, then a C# 9 extension method) and sketch the lowered while loop with its finally, including when that finally is left out.
Use the lowering to reason about cost and correctness: why List<T> returns a struct, why arrays and spans compile to for loops, and why disposal still runs on break or an exception.
Treat the pattern as an API design tool: a public struct GetEnumerator beside an explicit IEnumerable<T> lets a hot-path collection stay allocation-free in foreach while still working with LINQ.
## The pattern `foreach` binds to `foreach` does not require an interface. For `foreach (var x in c)` the compiler works out a **collection type**, an **enumerator type** and an **element type**, trying these routes in order: 1. If `c` is an **array**, it is enumerated as an array (and lowered specially, see below). 2. A **public instance method** `GetEnumerator()` that can be called with no arguments on the type of `c`. 3. Failing that, an implementation of **`IEnumerable<T>`** (the enumerator type is then `IEnumerator<T>`), or of the non-generic **`IEnumerable`**, whose element type is `object`. 4. Failing both, since **C# 9**, an accessible **extension method** named `GetEnumerator`. Whatever route wins, the returned enumerator type must have a public `bool MoveNext()` and a public, readable `Current` property. The type of `Current` is the element type; if the loop variable is declared with a different type, the compiler inserts an explicit conversion. Nothing else is required: no `Count`, no indexer, no `Reset`. The order matters. A type that has both a public `GetEnumerator()` and an explicit `IEnumerable<T>.GetEnumerator()` gets the public one, which is how `List<T>` hands `foreach` its struct `List<T>.Enumerator`. An extension `GetEnumerator` is only a last resort, so it cannot override a type's own method. ## What the loop is lowered into The compiler rewrites the statement into ordinary code, roughly: ```csharp // foreach (V v in c) body; becomes: E e = c.GetEnumerator(); try { while (e.MoveNext()) { V v = (V)e.Current; // a new variable on every iteration (C# 5 and later) // body } } finally { // dispose e, when e can be disposed } ``` What goes into that `finally` depends on the enumerator type `E`: - If `E` implements `IDisposable`, the `finally` calls `Dispose()`. On a struct enumerator this is a constrained call, so the struct is not boxed; on a class, a null check comes first. - If `E` is a `ref struct` with a public `Dispose()` method, that method is called by pattern (C# 8 and later). - If `E` is a non-sealed class, or an interface such as the non-generic `IEnumerator`, and is not known to be disposable, the compiler emits a run-time test, `e as IDisposable`, and disposes when it succeeds. - If `E` is a struct or a sealed class that is not disposable, there is no `try`/`finally` at all. Because disposal sits in a `finally`, it runs on **every exit** from the loop: running to the end, `break`, `return`, or an exception thrown by the body. `foreach` never calls `Reset`. ## Arrays, strings and spans skip the enumerator For a few types the compiler does not call `GetEnumerator` at all: | Collection expression | What `foreach` compiles to | |---|---| | single-dimensional array `T[]` | an indexed `for` loop over `Length` | | `string` | an indexed `for` loop over `Length` and the `char` indexer | | `Span<T>` and `ReadOnlySpan<T>` | an indexed `for` loop over `Length` and the indexer | | any other type | `GetEnumerator`, `MoveNext` and `Current`, as above | So `foreach` over an `int[]` costs the same as a hand-written `for` loop: no enumerator object, no `MoveNext` call, nothing to dispose. ## Why it is a pattern, not an interface The pattern dates from C# 1, before generics. It let a collection offer a strongly typed `Current` and a struct enumerator instead of boxing every element through `object IEnumerator.Current`. The reason still holds: most collections in the base class library expose a public `GetEnumerator()` that returns a struct and implement `IEnumerable<T>.GetEnumerator()` explicitly beside it. Your own types can do the same. A fixed-capacity `RingBuffer<T>` for a telemetry agent, as in the first example, needs nothing more than a public `GetEnumerator()` returning a small struct with `MoveNext` and `Current` to work in `foreach` without allocating. The extension route (C# 9) makes a type you do not own enumerable: the second example gives `System.Range` an extension `GetEnumerator`, so `foreach (int i in 1..4)` compiles. ## When binding fails - **CS1579**: "foreach statement cannot operate on variables of type '{0}' because '{0}' does not contain a public instance or extension definition for '{1}'". No route found a `GetEnumerator`. - **CS0202**: `GetEnumerator` was found, but its return type lacks a suitable public `MoveNext` method or public `Current` property. - **CS1640**: the type implements `IEnumerable<T>` for more than one unrelated `T` and has no `GetEnumerator` of its own, so the element type is ambiguous; cast to the instantiation you mean. - **CS8400**: the only `GetEnumerator` is an extension method and the project's `LangVersion` is below 9.
- If a C# type has a public GetEnumerator() and also implements IEnumerable<T>.GetEnumerator() explicitly, which one does foreach call?The public instance method. The pattern lookup runs first and only falls back to the interfaces when it finds no usable public `GetEnumerator()`. That is how `List<T>` gives `foreach` its struct `List<T>.Enumerator`, while code holding the same list as `IEnumerable<T>` gets the interface method's `IEnumerator<T>`. An extension `GetEnumerator` is consulted last, after both.
- Does a C# foreach call Dispose on an enumerator whose type does not implement IDisposable?It depends on the type. A struct or sealed class that is not disposable gets no `finally` at all. For a non-sealed class, or an interface such as `IEnumerator`, the compiler emits a run-time `e as IDisposable` test and disposes when it succeeds, because a derived type might implement it. A `ref struct` with a public `Dispose()` method is disposed by pattern since C# 8.
- Why is foreach over an int[] in C# no slower than a for loop?For a single-dimensional array, `string`, `Span<T>` or `ReadOnlySpan<T>`, the compiler never calls `GetEnumerator`. It lowers `foreach` to an indexed `for` loop over `Length` and the indexer, so there is no enumerator object, no `MoveNext` call and nothing to dispose.
- foreach only works on types that implement IEnumerable or IEnumerable<T>.
- foreach calls Reset on the enumerator before the first iteration.
- The enumerator is disposed only when the loop runs to the end.
- foreach over an array allocates an enumerator object on the heap.
- An extension method named GetEnumerator is never picked up by foreach.