4 ms·
var outer = 2; var btn = new Button() { Text = "Click Me" }; btn.Click += (obj, eventArgs) => { var local = outer + outer;
by nxn 15y ago
var outer = 2;
var btn = new Button()
{
Text = "Click Me"
};
btn.Click += (obj, eventArgs) =>
{
var local = outer + outer;
};
How is the above any different/better/worse than what javascript can do?
- MatthewPhillips 15y agoI reserve the right to be wrong here, but I'm pretty sure in your example outer will be be null on the onclick.
- MatthewPhillips 15y agoOk I tested it and you have access to outer here. I must be thinking of something else. Asynchronous web requests?
- chrisb 15y agoouter will be 2 A closure is created for the anonymous function, allowing access (by reference) to the non-local variables in the containing method.
- SideburnsOfDoom 15y agoOuter is (implicitly) typed as an int, so it cannot be null under any circumstances. The default value for ints is 0. However, outer will be 2 in this case. Environment capture makes it do what it looks like, just like javascript. I don't know what you mean by "has closures but not when evented."
- chc 15y agoIf outer were anything but 2 in the click handler, it wouldn't be a closure, which by definition closes over its environment.