dotnet / dotnet/csharpstandard

Awaiter GetResult returning by reference

Open
#1,152 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
C#
Stars
815
Forks
99
Avg merge
1d 14h
Merged PRs (30d)
16

Description

I was playing with this code in SharpLab:

```csharp
using System;
public class C {
public async void M() {
N(ref await new RT());
}
private void N(ref int r) {}
}

public class RT {
public Awaiter GetAwaiter() {
return new Awaiter();
}
public struct Awaiter : System.Runtime.CompilerServices.INotifyCompletion {
private static int k;
public bool IsCompleted => true;
public void OnCompleted(Action action) {
action();
}
public ref int GetResult() {
return ref k;
}
}
}
```

The `ref await` syntax causes an error:

> error CS1510: A ref or out value must be an assignable variable

That seems to be covered by the existing wording:

> 12.9.8.3 Classification of await expressions
>
> The expression `await t` is classified the same way as the expression `(t).GetAwaiter().GetResult()`. Thus, if the return type of `GetResult` is `void`, the *await_expression* is classified as nothing. If it has a non-`void` return type `T`, the *await_expression* is classified as a value of type `T`.

GetResult here returns `int` by reference, but the *await_expression* is classified as a value. So the compiler works as specified. Still, it might be good to add a note about this case.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.