Romasz Romasz - 28 days ago 9
C# Question

Why Elvis (?.) operator doesn't work with async-await?

Let's have a code like this (fragment of App.xaml.xs):

public class MethodClass
{
public async Task Job()
{
Debug.WriteLine("Doing some sob");
await Task.Delay(1);
}
}

public MethodClass MyClass = null;

protected async override void OnLaunched(LaunchActivatedEventArgs e)
{
await MyClass?.Job(); // here goes NullreferenceException
MyClass?.Job(); // works fine - does nothing


Why Elvis operator doesn't work with async-await? Am I missing something?

Rob Rob
Answer

Your code is equivalent to the following:

async void Main()
{
    var thing = new MethodClass();
    await thing.Job();
}
public class MethodClass
{
    public Func<Task> Job = null;
}

Clearly, you cannot await null - hence the NullReferenceException

Comments