While reviewing a codebase I noticed the following C# snippet:
What we are trying to do here is to simplify the null check on the transaction object by using a null-conditional operator (?.)
However this doesn’t work as expected when using async
/await
. If we would try to execute the code as-is, we would get a NullReferenceException
when the transaction object is null. Exactly the thing we are trying to avoid.
This is something that you can already notice if you look at the compiler warning we get:
The reason is that our await call- even if there's no result value – expect to get a Task
object back. Instead the result is null
and the compiler generated async\await
code internally can't deal with the null
value. Hence the NullReferenceException
when a value of Task
is expected.
If you really want to use the null-conditional operator you could rewrite the code like this:
More information:
Member access and null-conditional operators and expressions: - C# | Microsoft Learn