Why Elvis (?.) operator doesn't work with async-await?
The way await
is translated is that first, GetAwaiter()
is called on the awaited object (in your case, a Task
). It then does some other complicated things, but those are not relevant here:
await MyClass?.Job();
Compiles to:
var awaiter = MyClass?.Job().GetAwaiter();// more code
Since Task.GetAwaiter()
is an instance method and you're calling it with a null
Task
, you get a NullReferenceException
.
As a curiosity, it is possible to await
a null
awaitable, as long as its GetAwaiter()
is an extension method that accepts null
:
public class NullAwaitable { }public static class Extensions{ public static TaskAwaiter GetAwaiter(this NullAwaitable _) => Task.CompletedTask.GetAwaiter();}public class MethodClass{ public NullAwaitable Job() => new NullAwaitable();}MethodClass MyClass = null;await MyClass?.Job(); // works fine