title: C# under the hood code generation for lambdas within loops
body: <p>This question is based on the answer given by one of my favourite posters Mehrdad Afshari in <a href="https://stackoverflow.com/questions/1095707/what-is-the-exact-definition-of-a-closure">this</a> question about closure.</p>
  
  <p>I am having a hard time understand why C# generates the code the way it does......</p>
  
  <p>Here is the code in question </p>
  
  <pre><code>    static void Main(string[] args)
      {
  
          List&lt;string&gt; list = new List&lt;string&gt; { "hello world",  "TED", "goodbye world" };
  
          IEnumerable&lt;string&gt; filteredList1 = list;
  
          IEnumerable&lt;string&gt; filteredList2 = list;
  
          var keywords = new[] { "hello", "world" };
  
          foreach (var keyword in keywords)
          {
              //Will execute the following 
              //filteredList1 = filteredList1.Where(item =&gt; item.Contains("hello")).Where(item =&gt; item.Contains("world"));;
              string value = keyword;
              filteredList1 = filteredList1.Where(item =&gt; item.Contains(value));
  
              //Will execute the following 
              //filteredList2 = filteredList2.Where(item =&gt; item.Contains("world"))
              filteredList2 = filteredList2.Where(item =&gt; item.Contains(keyword));
          }
  
          Console.WriteLine("===================================================");
          Console.WriteLine("LIST 1");
          foreach (var s in filteredList1)  // closure is called here
              Console.WriteLine(s);
          Console.WriteLine("===================================================");
  
          Console.WriteLine("LIST 2");
          foreach (var s in filteredList2)  // closure is called here
              Console.WriteLine(s);
          Console.WriteLine("===================================================");
      }
  }
  </code></pre>
  
  <p>Gives the following output</p>
  
  <pre><code>===============
  LIST 1
  hello world
  ===============
  LIST 2
  hello world
  goodbye world
  ===============
  </code></pre>
  
  <p>My problem is that I don't understand why filteredList2 list not generating the same code as filteredList1. 
  It seems more sensible to that with each iteration of the  foreach (var keyword in keywords) should just append another .Where(item => item.Contains(keyword)) and pass in a copy keyword current value.  </p>
  
  <p>Why does it not do this? </p>
  
  <p><strong>EDIT</strong> : OK maybe I was not clear. I understand When and how the closure generated, however I don't understand <strong>WHY</strong> it is done like this. Surely it makes sense hat if a compiler detects a loop variable is being used then why can it not generate a temp variable and ultimately end up in the same situation as filteredList1.  Am I missing something here?
  May be there is some scenario where you would want to pass the same context to a lambda multiple times, but even then it always makes sense for the compiler to use local variable to store the value of loop variable when it is used as a context for a lambda.  </p>
  
  <p>To quote Jon Skeets definition of closure "To put it very simply, closures allow you to encapsulate some behaviour, pass it around like any other object, and still have access to the context in which they were first declared."</p>
  
  <p>Surely you guys can see that c# closure over loop variable loses the context of the loop variable in which it was first set.</p>
  
  <p>P.S. Please excuse the waffling I have a severe flu and trying to be concise is very difficult :-)</p>