C# Closures, why is the loopvariable captured by reference?

Well, that’s just how C# works. The lambda expression in your statement constructs a lexical closure, which stores a single reference to i that persists even after the loop has concluded.

To remedy it, you can do just the thing that you did.

Feel free to read more on this particular issue all around the Web; my choice would be Eric Lippert’s discussion here.

Leave a Comment