Say you have a button on your form. You attached an anonymous function to button's Click
event:
void Test()
{
int x = 10;
btn.Click += (sender, e) => { MessageBox.Show(x.ToString()); };
}
This works as expected and displays 10; means it can access local variables. My question is how and why? How does an anonymous function get access to the local context?
The actual problem I'm dealing with is that I need to upgrade (so to speak) this anonymous function to a regular function (event handler). But doing that means I'll lose access to the variable x. I can't pass it in as a parameter too because then I'll not be able to attach it to Click
event (signature mismatch). I can work around this by creating global variables and all that, but how do anonymous functions make it possible to access things that were outside their scope?
EventHandler handler = (sender, e) => { ... }
– Jon SkeetPropertyChangedCallback
that I had declared and assigned anonymously. I suspect this could be due to the anonymous method going out of scope and thus get wiped by GC and so wanted to try with a regular function. – dotNET