Mergasov Mergasov - 1 year ago 146
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 Source

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();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download