When i have a code block
static void Main()
{
foreach (int i in YieldDemo.SupplyIntegers())
{
Console.WriteLine(\"{0} is consumed by foreach iteration\
Simply put, iterator blocks (or methods with yield
statements, if you may) are transformed by the compiler into a compiler-generated class. This class implements IEnumerator
and the yield
statement is transformed into a 'state' for that class.
For instance, this:
yield return 1;
yield return 2;
yield return 3;
might get transformed into something similar to:
switch (state)
{
case 0: goto LABEL_A;
case 1: goto LABEL_B;
case 2: goto LABEL_C;
}
LABEL_A:
return 1;
LABEL_B:
return 2;
LABEL_C:
return 3;
Iterator blocks are can be seen as abstracted state machines. This code will be invoked by IEnumerator
's methods.