title: Unexpected behaviour when using foreach and lambdas
body: <p>I have the following code...</p>
  
  <pre><code>namespace ConsoleApplication2
  {
      public delegate void Task();
  
      class Scheduler
      {
          private List&lt;Task&gt; tasks = new List&lt;Task&gt;();
  
          public void AddTask(Task myTask)
          {
              tasks.Add(myTask);
          }
  
          public void Start()
          {
              foreach (var task in tasks)
                  task();
          }
      }
  
      class Program
      {
          static void Main(string[] args)
          {            
              var list = new List&lt;string&gt;() { "A", "B", "C" };
              var scheduler = new Scheduler();
              foreach (var item in list)
              {
                  scheduler.AddTask(() =&gt; { Console.WriteLine(item); });
              }
              scheduler.Start();
          }
      }
  }
  </code></pre>
  
  <p>The output is...</p>
  
  <pre><code>C
  C
  C
  </code></pre>
  
  <p>However, if I change the foreach part of the Main method to this:</p>
  
  <pre><code>    foreach (var item in list)
      {
          var i = item;
          scheduler.AddTask(() =&gt; { Console.WriteLine(i); });
      }
  </code></pre>
  
  <p>I get the following output:</p>
  
  <pre><code>A
  B
  C
  </code></pre>
  
  <p>My noobish assumption was that both programs should generate the same output. Can someone please explain why it's behaving that way?</p>