Tag: closure

Dot Net Gotcha #2 – Loop variables and Closures

This one is my favorite. Can you guess the output of this simple console application: One would expect to see numbers from 0 to 9 but here is the actual output of the app: OK that’s strange right? It turns out its like that by design. What you have there is a Closure over the loop variable. And closures in C# are done around variables and not around specific values of those variables – so that means that lambda expression gets to use the actual reference to the closed variable. Let me explain in little bit more detail: In first loop…