Like trying to fit a square peg in a round hole

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 plentyofStackOverflowquestions and blogposts 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:

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: