title: C# Closure works?
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/8898925/is-there-a-reason-for-cs-reuse-of-the-variable-in-a-foreach">Is there a reason for C#&#39;s reuse of the variable in a foreach?</a><br>
    <a href="https://stackoverflow.com/questions/9569334/looping-through-a-list-of-actions">Looping through a list of Actions</a>  </p>
  </blockquote>
  
  
  
  <p>today I encounter a problem about the C# foreach function, it didn't give me the proper result as I expected. here is the code:</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  
  namespace ConsoleApplication1
  {
  class Program
  {
      static void Main(string[] args)
      {
          int[] data = new int[] { 1, 2, 3, 4, 5 };
          List&lt;Func&lt;int&gt;&gt; actions = new List&lt;Func&lt;int&gt;&gt;();
          foreach (int x in data)
          {
              actions.Add(delegate() { return x; });
          }
          foreach (var foo in actions)
          {
              Console.WriteLine(foo());   
          }
          Console.ReadKey();
      }
  }
  }
  </code></pre>
  
  <p>when I Run it in console application and it has five 5 printed on the screen. Why? I just cann't understand. Have asked some people and they just said that there is closure in this code, But I am not very clear about this, I remember that in javascript , I often encounter the closure, but in above code, why there is closure? thx.</p>