Mergasov Mergasov - 5 months ago 96
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?


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();


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