59

I'm experiencing an interesting System.NullReferenceException whilst using the new null-conditional operator in C#. The following code gives me a NullReferenceException if "MyObject" is null:

await this.MyObject?.MyMethod()

I would've expected that the call to "MyMethod" would simply not be made if "MyObject" is null, or am I misunderstanding the purpose of the null-conditional operator?

2 Answers 2

83

You can add ?? Operator so if ?. returns null task use CompletedTask instead.

await (this.MyObject?.MyMethod() ?? Task.CompletedTask)

I would've expected that the call to "MyMethod" would simply not be made if "MyObject" is null.

Thats true. the ?. operator returns null task instead of calling MyMethod. the null reference exception is made because you cant await on null task. The task must be initialized.

1
  • 18
    I know this is very old at this point, but I would like to make a small note that if MyMethod() returns something you can also do var output = await (this.MyObject?.MyMethod() ?? Task.FromResult(default(T)));
    – Elw00t
    Commented Sep 25, 2019 at 17:02
13

A lot of discussion takes place around the awkwardness of null conditional in await. You can see some of it in the C# proposal Champion "Null-conditional await" #35. While the accepted answer works, I believe two extensions methods encapsulate the behavior better:

public static Task ForAwait(this Task task)
{
    return task ?? Task.CompletedTask;
}

public static Task<T> ForAwait<T>(this Task<T> task, T defaultValue = default)
{
    return task ?? Task.FromResult(defaultValue);
}

You would use them as: await (this.MyObject?.MyMethod()).ForAwait(). Note the extra parentheses! You can even specify your own default value, if default(T) is not what you want to return by default. I've seen other people do something similar and also add an extra parameter that would ConfigureAwait inside the method.

I would have loved to get rid of the ugly parentheses, somehow, but the language doesn't allow it (yet?).

1
  • Very nice. You could apply it even better as so: await (this.MyObject?.MyMethod()!).ForAwait(). Note the exclamation mark I added, this removes the 'Possible null dereference' warning in VS.
    – Stefan
    Commented Mar 2 at 12:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.