title: How can I capture the value of an outer variable inside a lambda expression?
body: <p>I just encountered the following behavior: </p>
  
  <pre><code>for (var i = 0; i &lt; 50; ++i) {
      Task.Factory.StartNew(() =&gt; {
          Debug.Print("Error: " + i.ToString());
      });
  }
  </code></pre>
  
  <p>Will result in a series of "Error: x", where most of the x are equal to 50.</p>
  
  <p>Similarly:</p>
  
  <pre><code>var a = "Before";
  var task = new Task(() =&gt; Debug.Print("Using value: " + a));
  a = "After";
  task.Start();
  </code></pre>
  
  <p>Will result in "Using value: After".</p>
  
  <p>This clearly means that the concatenation in the lambda expression does not occur immediately. How is it possible to use a copy of the outer variable in the lambda expression, at the time the expression is declared? The following will not work better (which is not necessarily incoherent, I admit):</p>
  
  <pre><code>var a = "Before";
  var task = new Task(() =&gt; {
      var a2 = a;
      Debug.Print("Using value: " + a2);
  });
  a = "After";
  task.Start();
  </code></pre>