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;
        };
    }
}

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...