title: How yield return works in c#
body: <p>I have following piece of code.</p>
  
  <pre><code>public static void main(string []args)
  {
  
    var intergers = GetCollection();
  
    foreach(var val in intergers)
    {
     console.writeline(val);
     }
  
  }
  
  public IEnumerable&lt;int&gt; GetCollection()
  {
  
    yield return 10;
  
    var obj = new MyClass();
    obj.performLargeAction();
  
    yield return 1;
  
    var obj = new MyClass();
    obj.perform();
  
    yield return 2;
  
    console.writeline("I am finished now");  
  }
  </code></pre>
  
  <p>Now, when I debug the code and see the foreach iteration, then I see that first time method executes till yield return 10 and then control goes back to foreach loop, on next iteration code after yield return 10 and till yield return 1 is executed and in next iteration it executes from line right after yield return 1 and till yield return and in next iteration it
  calls console.writeline();</p>
  
  <p>So, with this behavior, I am keen to know does .net pause the execution of the method which is returning IEnumerable and save its location counter or state to the stack and next iteration again pops the location and set it to program counter or location counter and all these thing or </p>
  
  <p><strong>I have read something yield is a c# feature, so this above piece of code is converted to IL and that yield part is replaced with a class called YieldEnumerator which stores state, current and other thing. but still I could not understand its actual functioning. So, I would like to know its internal working form starting to end.</strong></p>