C# Error CS8175 – Cannot use ref local ‘{0}’ inside an anonymous method, lambda expression, or query expression

C# Error

CS8175 – Cannot use ref local ‘{0}’ inside an anonymous method, lambda expression, or query expression

Reason for the Error & Solution

Cannot use ref local inside an anonymous method, lambda expression, or query expression

Remember that expression capturing is a compile-time operation and by-reference refers to a run-time location.

Example

The following sample generates CS8175:

// CS8175.cs (10,21)

using System;
class C
{
    void M()
    {
        ref readonly int x = ref (new int[1])[0];
        Action a = () =>
        {
            int i = x;
        };
    }
}

To correct this error

Removing the use of by-reference variables corrects this error. In the example code, this can be done by first assigning the value of the referenced variable to a by-value variable:


using System;
class C
{
    void M()
    {
        ref readonly int x = ref (new int[1])[0];
        int vx = x;
        Action a = () =>
        {
            int i = vx;
        };
    }
}