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);
}