My mistake was to think that the value of i is passed on to the event handler like a function parameter and placed on the stack. Don’t make that mistake. The value of i actually closes on you, I mean on the event handler, or the inner function. So variable i is a closure variable, while the inner function is a closure function.
Again don’t make the mistake that assigning the event handler to the onclick event actually calls the event handler. It’s an event handler so it can be called even after the outer function has been out of scope.
So you ask, what happens to the value of i then? Well for closure situations like this, the compiler creates a special context object containing the closure variables so that closure functions, when they get executed, will have access to these variables even if the function that the closure variables are declared in are already out of scope.
- Outer Variable Trap in C#
- Closing over the loop variable considered harmful in C#
I can’t guarantee you to become a closure relationship expert, but after going through the readings and links above, I can guarantee you to become a closure programming expert ;).