9. May 2012 14:04
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.
Here is some code, as simple as I could make it, that produces the warning and illustrates the behaviour:
var actions = new Action;
for (int i = 0; i < actions.Length; i++)
actions[i] = () => Console.WriteLine(i);
foreach (var action in actions)
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: