#1,191 – Lambda Can’t Capture ref or out Parameters
September 26, 2014 2 Comments
Lambda expressions can make use of variables declared in a containing scope, i.e. outside of the expression itself. They cannot, however, use variables that are defined as ref or out parameters in an outer scope.
In the example below, it’s a compile-time error to include the valOut parameter in the lambda expression.
static void SomeMethod(int valIn, out int valOut) { int local; Action doCalc = () => { local = valIn * 2; // this is ok valOut = valIn * i; // this is not--compile-time error }; }
As an alternative, you can assign a value returned by the lambda to an out parameter.
static void SomeMethod(int valIn, out int valOut) { // Ok to assign result of lambda to // out parameter Func<int> doCalc2 = () => valIn * 2; valOut = doCalc2(); // Allowed }