Fun with Anonymous Methods

A recent thread over an internal alias really drilled home some details of how Anonymous Methods in C# 2.0 work…

If you have the Whidbey Beta you can check it out for yourself, but try to figure it out without running the code…

What does this code print:

using System;

using System.Threading;

class Program

{

    static void Main(string[] args)

    {

        for (int i = 0; i < 10; i++)

        {

            ThreadPool.QueueUserWorkItem(delegate { Console.WriteLine(i); }, null);

        }

        Console.ReadLine();

    }

}

How does this change if you tweak it like this:

using System;

using System.Threading;

class Program

{

    static void Main(string[] args)

    {

        for (int i = 0; i < 10; i++)

        {

            int j = i;

            ThreadPool.QueueUserWorkItem(delegate { Console.WriteLine(j); }, null);

        }

        Console.ReadLine();

    }

}

And most importantly, why?