An Answer

From my consultations with C# insiders, looks like ~"loop variables are special"~ meaning that the compiler won’t make private copies for "enclosured" or "outer" variables. The issue is the difference between "instantiating" variables and "initializing" them in the C# spec http://msdn2.microsoft.com/en-us/vcsharp/aa336809.aspx (see "Outer Variables" in section 7.14.4 around page 206).

Proof?  The following works as expected … introducing the non-"special" variable j causes the compiler to make copies of it for each closure.

static void Main(string[] args)
{
    for (var i = 0; i < 40; i++)
    {
        var j = i;
        new Thread(() => { Thread.Sleep(1); Console.Write("{0} ", j); }).Start();
    }
    Console.WriteLine();
}

"Special" is one of those words, like "simple," that should cause concern. "Special" means ~"varies from the normal way of things."~ Some people think it’s a euphemism for "good"; in my experience, special cases lead to nasty surprises, like this one.

"Simple" is subjective. To some people it means "flattened, explicit, without ambiguity." To others it means "short or small, even if abstracted, implicit, or ambiguous." I’ve seen grown engineers argue for hours that their solution is "simpler" than the other guy’s, with the two of them meaning exactly the opposite by the term.

Advertisements

~ by rebcabin on April 16, 2008.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: