Mergasov Mergasov - 1 month ago 22
C# Question

Null conditional operator and LINQ

There is my code (it is used in net core project):

var list = await user.RelatedEntityCanBeNull?.ToListAsync();


It throws NullReferenceException if RelatedEntityCanBeNull is null for user. Why doesn't the expression return null?

Answer

The await operator expects an awaitable Task object. The Null conditional operator returns null and await null results in a NullReferenceException.

You have to change your code to

List list = null;
if (user?.RelatedEntityCanBeNull != null)
   list = await user.RelatedEntityCanBeNull.ToListAsync();

or

var list = user?.RelatedEntityCanBeNull == null ? null : await user.RelatedEntityCanBeNull.ToListAsync();