title: Why does a yield in a foreach-iteration through an array within a lock crash the VS2010 compiler?
body: <p>A question related to the C#/.NET compiler used in Visual Studio 2010: During the development of a project, a colleague encountered a situation where the VS2010 compiler would crash when using existing code inside a lock. We took the code apart line-by-line to eventually come to the conclusion that using a <code>yield return</code> inside a <code>foreach</code> through an array within a lock statement would crash the compiler. The issue can be reproduced with the following code:</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  
  namespace PlayGround
  {
      public static class Program
      {
          private static readonly object SyncRoot = new object();
  
          private static IEnumerable&lt;int&gt; EnumerableWithLock()
          {
              lock (SyncRoot)
              {
                  foreach (var i in new int[1])
                  {
                      yield return i;
                  }
              }
          }
  
          public static void Main()
          {
              foreach (var i in EnumerableWithLock())
              {
                  Console.WriteLine(i);
              }
          }
      }
  }
  </code></pre>
  
  <p>We continued to test this reproduction sample on Visual Studio 2013 and it did not exhibit the same problem. This compiler issue seems to be related to the compiler used in VS2010, and might or might not have the same problem in VS2012 (we do not have access to it for testing purposes). Furthermore, we have tested that using a regular <code>for</code> loop does not crash. The question therefore is, <strong>why does the VS2010 compiler crash?</strong> What is it doing that confuses it so much?</p>
  
  <p>(Yes, this is mostly a question for interests-sake to learn about the compiler)</p>