float4x4

Computer graphics and stuff

For loops and lambda’s

No Comments »

Last month I went to the Microsoft TechDays 2011 in Antwerp and there were two presentations I really wanted to see. One of those was Rob Miles‘ presentation on XNA for the Windows Phone. A great presentation that made me wish I had this guy as professor when I was at university. Go see him if you ever have the chance, just don’t expect too much from his jokes!

The other presentation was one on C++11 by Boris Jabes. Strangely, few people seemed interested in the topic. The room was pretty empty compared to other presentations. Nevertheless Boris really gave an awesome talk and really made me think twice about C#’s using statements. Especially if you’re a SharePoint developer, these things are a dime a dozen. Check out the video, I really enjoyed it.

There was something very specific about that presentation that got me in a rush to get home. One of his slides showed this piece of C# code:


List<Action> actions = new List<Action>();

for (int counter=0; counter < 10; counter++)
{
actions.Add(() => Console.WriteLine(counter));
}

foreach(Action action in actions)
{
action();
}

He asked the audience what the result would be…

I suppose anyone’s first guess would have been 0 through 9. Of course whenever a question like that is asked, there surely is a catch somewhere! Someone in the audience figured that out and said it would display ten 9′s, Boris agreed.

It seems C# doesn’t capture the value of a primitive in a lambda but a reference to it. Hence, the result of each action() call would be the last value set to counter. But wait a minute, is 9 really the last value set to counter? If the value of counter is 9, then the expression counter < 10 equals true, and thus the loop would continue. The for loop will only end if counter is 10 or higher! So why would the result be ten 9′s?

Even though there weren’t that many people in the room, there were still enough to stop me from asking and possibly get laughed at for being stupid. I decided to take the safe route and just try it out at home. The result was as expected, ten 10′s were displayed! Mystery solved! Boris’ talk was really one of my two favourites and if I ever get a chance to listen to him again I certainly will. Perhaps I will point out the correct result… after the talk when everybody else is gone ;-)

Leave a Reply