title: yield return method optimized away when it shouldn't be
body: <p>I've stumbled upon a test problem of my library where a <code>yield return</code> gets optimized for reasons I don't understand.</p>
  
  <p>Proof of concept code:</p>
  
  <pre><code>static IEnumerable&lt;int&gt; Sample(int count)
  {
      for (int i = 0; i &lt; count; i++) yield return i;
  }
  static IEnumerable&lt;int&gt; ForEach(IEnumerable&lt;int&gt; items, Action&lt;int&gt; action)
  {
      foreach (int item in items) { action(item); yield return item; }
  }
  static void After(IEnumerable&lt;int&gt; items, Action action)
  {
      action();
  }
  
  static void Main(string[] args)
  {
      int item = -1;
      After(ForEach(Sample(10), v =&gt; item = v), () =&gt; Console.WriteLine(item));
      Console.WriteLine(item);
      Console.ReadKey();
  }
  </code></pre>
  
  <p>I expect the output to be <code>9</code> then <code>9</code>.</p>
  
  <p>The actual output is <code>-1</code> then <code>-1</code>.</p>
  
  <p>The initialization of <code>IEnumerable</code>s at <code>Sample</code> and <code>ForEach</code> is optimized away, and as a side effect <code>item</code> inside <code>Main</code> is never changed.</p>
  
  <p>Why hasn't <code>Sample</code> been iterated at <code>ForEach</code>?</p>
  
  <p>Am I <em>really</em> required to iterate <code>items</code> at <code>After</code>?</p>
  
  <p>If yes, why have the optimization be so deep that even the iteration at <code>ForEach</code> is halted until provoked, making the output <code>-1</code> then <code>9</code> possible too?</p>