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

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