HomeCSharpC# Error CS8178 – ‘await’ cannot be used in an expression containing a call to ‘{0}’ because it returns by reference

C# Error CS8178 – ‘await’ cannot be used in an expression containing a call to ‘{0}’ because it returns by reference

C# Error

CS8178 – ‘await’ cannot be used in an expression containing a call to ‘{0}’ because it returns by reference

Reason for the Error & Solution

‘await’ cannot be used in an expression containing a call to because it returns by reference

Example

The following sample generates CS8178:

using System;
using System.Threading.Tasks;

class TestClass
{
    int x;
    ref int Save(int y)
    {
        x = y;
        return ref x;
    }

    async Task TestMethod()
    {
        Save(1) = await Task.FromResult(0);
    }
}

To correct this error

Changing the use of the return by reference to be synchronous corrects the error:

    async Task TestMethod()
    {
        var x = await Task.FromResult(0);
        Save(1) = 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...