How does the compiler-generated state machine for an iterator method actually work internally, and what class does it implement?
Short answer
The compiler transforms an iterator method's body into a hidden, compiler-generated class implementing IEnumerable /IEnumerator , with a numeric 'state' field tracking exactly which yield point execution last paused at — calling MoveNext() resumes execution from that saved…
Advertisement
AModel answer
The compiler transforms an iterator method's body into a hidden, compiler-generated class implementing IEnumerable<T>/IEnumerator<T>, with a numeric 'state' field tracking exactly which yield point execution last paused at — calling MoveNext() resumes execution from that saved state, runs until the next yield (or the method's end), saves the new state, and returns whether a new value was produced.
// Conceptual illustration of the compiler-generated state machine:
// class <CountToThree>d__0 : IEnumerable<int>, IEnumerator<int> {
// int state;
// int current;
// bool MoveNext() { switch (state) { case 0: current = 1; state = 1; return true; case 1: ... } }
// }Real-world example
Understanding what actually happens 'under the hood' when debugging or reasoning about an iterator method's performance characteristics.
Likely follow-ups
- Why does each separate call to GetEnumerator() on the SAME iterator method produce an entirely INDEPENDENT state machine instance?
Related topics