#1,191 – Lambda Can’t Capture ref or out Parameters

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
        }

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #1,191 – Lambda Can’t Capture ref or out Parameters

  1. Pingback: Dew Drop – September 26, 2014 (#1864) | Morning Dew

  2. Phạm Tuân says:

    Reblogged this on Phạm Tuân blog.

Leave a comment