I have the following code...
namespace ConsoleApplication2
{
    public delegate void Task();
    class Scheduler
    {
        private List<Task> tasks = new List<Task>();
        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<string>() { "A", "B", "C" };
            var scheduler = new Scheduler();
            foreach (var item in list)
            {
                scheduler.AddTask(() => { Console.WriteLine(item); });
            }
            scheduler.Start();
        }
    }
}
The output is...
C
C
C
However, if I change the foreach part of the Main method to this:
    foreach (var item in list)
    {
        var i = item;
        scheduler.AddTask(() => { Console.WriteLine(i); });
    }
I get the following output:
A
B
C
My noobish assumption was that both programs should generate the same output. Can someone please explain why it's behaving that way?
 
     
    