Saturday, May 26, 2012

Closure in a Loop Revisited (C# 5.0)

I've come across something today that has prompted me to write a fast post to update this previous one.

To my surprise, I read here that the way closures trapping loop variables work is being changed in C# 5.0. I felt quite shocked, as the way it works now is the correct way. I don't mind how many developers find it confusing (of course I found it terribly confusing before I fully grasped the idea), Programming is not an easy art, and it demands from artists (us) practice, effort and devotion. So if you're using closures you should know that Closures trap Variables, not values, meaning that if your loop is updating the variable, it's also updated for the closure(s) that have trapped it.

Seeking to learn more about this change I found this post by the very Eric Lippert

In C# 5, the loop variable of a foreach will be logically inside the loop, and therefore closures will close over a fresh copy of the variable each time. The "for" loop will not be changed. We return you now to our original article.

OK, good it's changing only for the foreach loop, not for for loops. I still find it unnecessary, but have to admit that the arguments given by Eric makes some good sense. However, probably this adds even more confusion to the issue:

  • On one side, people who knew how closures and loops worked before, will learn about this new "feature" and will be aware of things working differently between for and foreach, so no problem with them (us)
  • On the other side, people who were confused about closures and loops before, probably won't learn about this new feature, and suddenly, they can painfully hit a case where replacing a foreach with a for will change the behaviour of their code

Update 2012/05/29 I've just found this complementary question

No comments:

Post a Comment