title: C# Func: access local variables in a block
body: <p>Say I have this block of code in C#:</p>
  
  <pre><code>static void Main(string[] args)
  {
      List&lt;Func&lt;int&gt;&gt; fs = new List&lt;Func&lt;int&gt;&gt;();
  
      for (int i = 0; i &lt; 5; i++)
          fs.Add(() =&gt; { return i; });
  
      for (int i = 0; i &lt; 5; i++)
          Console.WriteLine(fs[i]());
  
      Console.ReadLine();
  }
  </code></pre>
  
  <p>When I run it, I expected it to print</p>
  
  <pre><code>0
  1
  2
  3
  4
  </code></pre>
  
  <p>but it prints </p>
  
  <pre><code>5
  5
  5
  5
  5
  </code></pre>
  
  <p>instead. My understanding is that the code in Func only keeps an address to <code>i</code> instead of getting the value of <code>i</code>, and this approach should be avoided. </p>
  
  <p>So my question is that, is there a way to capture the local variables and pass them into <code>Func</code> by value?</p>