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
