C# Error CS1988 – Async methods cannot have ref, in or out parameters

C# Error

CS1988 – Async methods cannot have ref, in or out parameters

Reason for the Error & Solution

Async methods cannot have ref, in or out parameters

ref parameters are not supported in async methods because the method may not have completed when control returns to the calling code. Any changes to the referenced variables will not be visible to the calling code, resulting in a CS1988 error.

Example

The following sample generates CS1988:

class C
{
    async Task M(ref int left, ref int right)
    {
        await Task.Run(() =>
        {
            left = 1;
            right = 2;
        });
    }
}

To correct this error

One reason to use the ref keyword is that a method conceptually has more than one result but implemented with more than one ref parameter. In this case, correcting the error can be achieved by transforming the method to return a single result through the use of a tuple:

    async Task<(int,int)> M(int left, int right)
    {
        await Task.Run(() =>
        {
            left = 1;
            right = 2;
        });

        return (left, right);
    }

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