If I have a method that takes an argument of type Action
, for example:
public void Foo(Action bar)
{
bar?.Invoke();
}
And I wish to pass it a lambda that uses a local variable, e.g.:
private void SomeEvent(object sender, SomeEventArgs e)
{
foo(() => { e.Cancel = true; });
}
Will this lambda execute as expected with respect to the use of the local variable, in this case, e
? What I mean is, When foo()
is called and in turn attempts to call the lambda, will it know e
? Or will e
be out of scope and I should do something like the 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);
}