HomeCSharpC# 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

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

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...