liveBook · Manning

IEnumerator<T>

As explained in C# Concurrency: Asynchronous and multithreaded programming

IEnumerator<T> is a .NET generic interface that exposes the current value of a sequence and advances enumeration to the next value.

IEnumerator<T> is the execution interface behind generic sequence enumeration. It exposes the current value and advances with MoveNext(), allowing foreach and other sequence consumers to work without knowing the collection’s representation. section 2.2

The compiler can rewrite an iterator method into an enumerable object plus an enumerator class. The generated enumerator stores progress, assigns Current at each step, and returns false when enumeration finishes. section 2.2

Manual iterator state

A hand-written enumerator can use a step field and switch in MoveNext(): step 0 assigns the first value, step 1 assigns the second, and the terminal step returns false. Current exposes the assigned value. section 2.2

   private int _step = 0;                           #1
   public bool MoveNext()
   {
      switch(_step)
      {
         case 0:
            Step0();
            ++_step;
            break;
         case 1:
            Step1();
            ++_step;
            break;
         case 2:
            return false;                           #2
      }
      return true;
   }

Inspect the state-machine-style MoveNext implementation that advances through values and signals completion. section 2.2

How C# Concurrency: Asynchronous and multithreaded programming covers it

How deep it goes
Explains Current, MoveNext, compiler rewriting, and a manual state machine, while leaving implementation details outside the shown skeleton.
Examples
Uses list-backed enumeration, yield return, and a manually implemented enumerator with Current and step-based MoveNext.
What it assumes
Assumes familiarity with C# methods and interfaces while teaching sequence enumeration from the IEnumerable<T> relationship downward.
What you can do after
Evaluate how yield return becomes an enumerator and implement a basic sequence state machine in C#.
How it connects
Connects generic enumeration to IEnumerable<T>, foreach, yield return, iterator methods, and compiler-generated classes.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C# Concurrency: Asynchronous and multithreaded programming. The section links point to the parts of the book it draws on.