Sean Blakemore's Blog

Like trying to fit a square peg in a round hole

9. May 2012 14:04
by Sean
7 Comments

What JavaScript taught me about C# – Understanding ‘Access to modified closure’

9. May 2012 14:04 by Sean | 7 Comments

Background

If you’ve spent any time writing C# using a copy of ReSharper you will have come across the phrase ‘Access to modified closure’. It’s a well known warning and there are plenty of StackOverflow questions and blog posts about it.

I’ve personally run up against this many times, and although I know what to do when it bites me, I’ve never really understood why it was happening. It just never really clicked for me.

Not until recently that is, when I decided it was time for me to become a JavaScript programmer instead of a jQuery programmer and actually learn the language properly!

The Warning

Here is some code, as simple as I could make it, that produces the warning and illustrates the behaviour:

var actions = new Action[5];

for (int i = 0; i < actions.Length; i++)
    actions[i] = () => Console.WriteLine(i);

foreach (var action in actions)
    action();

The ‘Access to modified closure’ is referring to the use of ‘i’, the loop variable, inside the lambda and being passed to ‘Console.WriteLine’. If you haven’t run into this before you’ll be surprised to find that this code will produce the following output:

5
5
5
5
5

More...