When you implement IEnumerable<T> and IEnumerator<T> by hand in C#, which members must you write and what does each one promise?
answer
- a source of cursors vs one cursor
- generic interfaces inherit older ones
- seven members across two types
- Current undefined outside the walk
- Reset exists but nobody calls it
basics
~20 sIEnumerable<T> needs GetEnumerator() plus the non-generic one, each returning a fresh cursor. IEnumerator<T> needs MoveNext, Current, the non-generic Current, Reset and Dispose; Current is undefined before the first MoveNext and after the end, and foreach never calls Reset.
solid answer
~40 s`IEnumerable<T>` is a source of cursors: `GetEnumerator()`, plus the non-generic `IEnumerable.GetEnumerator()` that usually forwards to it, must return a new, independent enumerator on every call. `IEnumerator<T>` is one walk; because it inherits `IEnumerator` and `IDisposable`, you write `MoveNext()`, `T Current`, `object IEnumerator.Current`, `Reset()` and `Dispose()`. A new enumerator sits before the first element; `MoveNext()` advances and returns whether an element is available; `Current` returns the same element until the next `MoveNext()` and is undefined before the first one and after the end. `Dispose()` is called by `foreach` on every exit, so it releases resources. `Reset()` is legacy: `foreach` and LINQ never call it, and many implementations throw `NotSupportedException`.
code
csharp · 29 linesusing System.Collections;
var window = new Window<string>(["a", "b", "c"]);
foreach (var outer in window)
foreach (var inner in window) // two independent cursors
Console.Write($"{outer}{inner} ");
Console.WriteLine();
Console.WriteLine(window.Count(s => s != "b")); // LINQ binds to IEnumerable<T>: 2
IEnumerator<int> e = new List<int> { 7 }.GetEnumerator();
Console.WriteLine(e.Current); // before MoveNext: 0
try { _ = ((IEnumerator)e).Current; }
catch (InvalidOperationException ex) { Console.WriteLine(ex.Message); }
sealed class Window<T>(T[] items) : IEnumerable<T>
{
public IEnumerator<T> GetEnumerator() => new Cursor(items); // fresh cursor per call
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
private sealed class Cursor(T[] items) : IEnumerator<T>
{
private int _index = -1;
public T Current => items[_index];
object? IEnumerator.Current => Current;
public bool MoveNext() => _index < items.Length && ++_index < items.Length;
public void Reset() => _index = -1;
public void Dispose() { }
}
}go deeper
Recall the split: IEnumerable<T> hands out enumerators, IEnumerator<T> walks one sequence with MoveNext and Current.
List all the members a hand-written pair needs, including the inherited non-generic ones and Dispose, and state the contract: fresh cursor per call, Current undefined outside the walk.
Review a hand-written enumerator for the classic bugs: GetEnumerator returning this, work done in Current, resources released only at the end, and Reset relied on.
Decide when a team should hand-write enumerators at all; usually forwarding or a yield iterator is enough, and a struct enumerator is reserved for measured hot paths.
## Two interfaces, two jobs The enumeration contract in .NET is split across two interfaces with different roles: - **`IEnumerable<T>`** is a **source of cursors**. It has one member, `GetEnumerator()`, and each call returns a new enumerator positioned before the first element. A type that implements it says "you can walk me, as many times as you like". - **`IEnumerator<T>`** is **one cursor**: one walk in progress, with its own position. It moves forward only and is used by one consumer. Both inherit older, non-generic interfaces: `IEnumerable<T> : IEnumerable` and `IEnumerator<T> : IDisposable, IEnumerator`. That inheritance is why a hand-written implementation needs more members than the generic interfaces seem to declare. ## The members you write | Member | Declared on | What it promises | |---|---|---| | `IEnumerator<T> GetEnumerator()` | `IEnumerable<T>` | a fresh, independent enumerator per call | | `IEnumerator IEnumerable.GetEnumerator()` | `IEnumerable` | the same, untyped; usually forwards to the generic one | | `bool MoveNext()` | `IEnumerator` | advance; `true` if an element is now available | | `T Current { get; }` | `IEnumerator<T>` | the element at the current position | | `object IEnumerator.Current { get; }` | `IEnumerator` | the same element as `object` | | `void Reset()` | `IEnumerator` | go back before the first element (optional in practice) | | `void Dispose()` | `IDisposable` | release whatever the walk holds | So implementing both interfaces by hand means seven members: two on the enumerable, five on the enumerator. The non-generic ones are normally explicit interface implementations that forward to the generic ones, as in the example. ## The promises in detail The comments on `IEnumerator` and `IEnumerator<T>` in the runtime source spell out the first three points; the last two are how the base class library's enumerators behave and what `foreach` relies on: 1. A new enumerator is **positioned before the first element**; the first `MoveNext()` brings the first element into view. 2. `Current` is **undefined before the first `MoveNext()`** and after a `MoveNext()` that returned `false`. The base class library's `List<T>.Enumerator.Current` returns `default(T)` there, while its explicit `IEnumerator.Current` throws `InvalidOperationException` ("Enumeration has either not started or has already finished."). Callers must not rely on either. 3. Reading `Current` several times without an intervening `MoveNext()` returns the **same** element; `Current` must not advance. 4. Once `MoveNext()` has returned `false`, well-behaved enumerators keep returning `false`; the example's cursor guards against stepping past the end for that reason. 5. `Dispose()` is called by `foreach` in a `finally` block on every exit, so it is where a file handle, a database reader or a rented buffer is released. Make it safe to call more than once. Collections in the base class library add one rule of their own: they record a version number and throw `InvalidOperationException` from `MoveNext()` when the collection changes during the walk. A hand-written enumerator over a mutable type may do the same. ## `Reset` is a legacy member `Reset()` came with the non-generic `IEnumerator` in .NET Framework 1.0, before generics. `foreach` never calls it, and neither do the LINQ operators. The source comment says the preferred behaviour is to return the exact same enumeration again, but many implementations simply throw `NotSupportedException`, and enumerators the compiler generates for `yield` methods always do. Code that wants to walk a sequence again should call `GetEnumerator()` again, which is exactly what `IEnumerable<T>` is for. ## Mistakes in hand-written implementations - **Returning `this` from `GetEnumerator()`**, so the collection is its own cursor. A nested `foreach` over the same object, or a LINQ call such as `items.Zip(items)`, then shares one position and produces wrong results. The example's nested loop prints all nine pairs because each `GetEnumerator()` call creates a new `Cursor`. - **Implementing only the non-generic `IEnumerable`.** `foreach` then sees `object` elements; value types are boxed on every `Current` and the loop variable needs a cast. - **Doing work in `Current`** (reading a file, computing a value) instead of in `MoveNext()`, which breaks the "same element on repeated reads" promise. - **Forgetting that the enumerator is disposable.** An enumerator that opens a resource in `GetEnumerator()` and only closes it when `MoveNext()` returns `false` leaks it whenever a consumer stops early. In practice most types do not write a cursor class at all: they forward to an inner collection's enumerator, or write an iterator method with `yield return`, which the compiler turns into such a class. Writing the members by hand is worth it for a struct enumerator on a hot path or for a cursor over an unusual storage layout, such as a ring buffer that wraps around.
- In C#, what goes wrong if a collection implements IEnumerable<T> and IEnumerator<T> on one class and returns this from GetEnumerator()?Every `foreach` and every LINQ operator then shares one position. A nested `foreach` over the same object advances the outer loop's cursor, `items.Zip(items)` pairs elements wrongly, and a second enumeration starts wherever the first one stopped. `IEnumerable<T>` promises a fresh, independent enumerator per `GetEnumerator()` call; returning `this` breaks that promise.
- Why do C#'s generic IEnumerator<T> implementations still need a Reset method and a non-generic Current?`IEnumerator<T>` inherits the non-generic `IEnumerator` from .NET Framework 1.0, which declares `MoveNext()`, `object Current` and `Reset()`, and it inherits `IDisposable`. An implementation must supply them all; the usual approach implements `IEnumerator.Current` and `Reset()` explicitly, forwarding `Current` and either restarting or throwing `NotSupportedException` from `Reset()`.
- IEnumerable<T> and IEnumerator<T> are interchangeable names for the same contract.
- foreach calls Reset before it starts, so Reset must always be implemented.
- Current is guaranteed to throw before the first MoveNext.
- Returning this from GetEnumerator is fine when the collection is small.
- Dispose is optional because foreach only calls it when the loop finishes normally.