c# - Should local variables be used in lambda statements when passed as delegates? -
if have method takes argument of type action, example:
public void foo(action bar) { bar?.invoke(); } and wish pass lambda uses local variable, e.g.:
private void someevent(object sender, someeventargs e) { foo(() => { e.cancel = true; }); } will lambda execute expected respect use of local variable, in case, e? mean is, when foo() called , in turn attempts call lambda, know e? or e out of scope , should following instead?
private void someevent(object sender, someeventargs e) { foo((someeventargs a) => { a.cancel = true; }, e); } public void foo(action<someventargs> bar, someeventargs e) { bar?.invoke(e); }
yes, should work expected. called "variable capture", , explained here.
in example, e variable captured, won't go out of scope.
Comments
Post a Comment