title: Algorithm for implementing C# yield statement
body: <p>I'd love to figure it out myself but I was wondering <strong>roughly what's the algorithm for converting a function with yield statements into a state machine for an enumerator?</strong> For example how does C# turn this:</p>
  
  <pre><code>IEnumerator&lt;string&gt; strings(IEnumerable&lt;string&gt; args)
   { IEnumerator&lt;string&gt; enumerator2 = getAnotherEnumerator();     
     foreach(var arg in arg) 
      { enumerator2.MoveNext();
        yield return arg+enumerator.Current;
      } 
   }
  </code></pre>
  
  <p>into this:</p>
  
  <pre><code>bool MoveNext()
   { switch (this.state)
      {
          case 0:
              this.state = -1;
              this.enumerator2 = getAnotherEnumerator();
              this.argsEnumerator = this.args.GetEnumerator();
              this.state = 1;
              while (this.argsEnumerator.MoveNext())
              {
                  this.arg = this.argsEnumerator.Current;
                  this.enumerator2.MoveNext();
                  this.current = this.arg + this.enumerator2.Current;
                  this.state = 2;
                  return true;
  
                state1:
                  this.state = 1;
              }
              this.state = -1;
              if (this.argsEnumerator != null) this.argsEnumerator.Dispose();
              break;
  
          case 2:
              goto state1;
      }
      return false;
  }
  </code></pre>
  
  <p>Of course the result can be completely different depending on the original code.</p>