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

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