HomeCSharpC# Error CS8177 – Async methods cannot have by-reference locals

C# Error CS8177 – Async methods cannot have by-reference locals

C# Error

CS8177 – Async methods cannot have by-reference locals

Reason for the Error & Solution

Async methods cannot have by-reference locals

To manage asynchronous state, async methods use a state machine, capturing variable state in closures implemented in compiler-generated classes and properties. A local variable reference (on the stack) cannot be captured within the instance of a class in the heap, so the compiler issues an error.

Example

The following sample generates CS8177:

// CS8177.cs (20,26)

using System.Threading.Tasks;

class E
{
    public class Enumerator
    {
        public ref int Current => throw new System.NotImplementedException();
        public bool MoveNext() => throw new System.NotImplementedException();
    }

    public Enumerator GetEnumerator() => new Enumerator();
}

class C
{
    public async static Task Test()
    {
        await Task.CompletedTask;

        foreach (ref int x in new E())
        {
            System.Console.Write(x);
        }
    }
}

To correct this error

Changing the variable declaration to remove the ref modifier corrects this error:

class C
{
    public async static Task Test()
    {
        await Task.CompletedTask;

        foreach (int x in new E())
        {
            System.Console.Write(x);
        }
    }
}

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...