When conditionally awaiting a task using the null coalescing operator inside a string interpolation, I got an unexpected compilation error that my async method lacks an await, and that await isn't possible outside of an async context:
using System;
using System.Threading.Tasks;
public class Program
{
public static async Task Main()
{
Task<string> isNull = null;
var result = "World";
var helloWorld = $"Hello {await (isNull ?? Task.FromResult(result))}";
Console.WriteLine(helloWorld);
}
}
Compilation error (line 10, col 29): The name 'await' does not exist in the current context
Compilation error (line 6, col 27): This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
I assume this is due to some compilator details that I am not aware of, and can't be avoided, but I would like to understand it.