4

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?

Ilya Loskutov
  • 1,967
  • 2
  • 20
  • 34
  • 1
    Talking about accessing `user` properties, shouldn't it be `user?.RelatedEntityCanBeNull?.ToListAsync();`? You access `user` without null-conditional operator, and it is null, and it gives an error. However, I am not sure how `await` does work with `null` tasks. – Yeldar Kurmangaliyev Nov 01 '16 at 09:15
  • 3
    I suspect it's because you're awaiting a null `Task` here. – Charles Mager Nov 01 '16 at 09:16
  • @Yeldar Kurmangaliyev, I checked user explicitly. It's not null – Ilya Loskutov Nov 01 '16 at 09:23
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – mybirthname Nov 01 '16 at 09:25
  • Try to use `user.RelatedEntityCanBeNull.GetValueOrDefault().ToListAsync()` (if available) – Mehmood Nov 01 '16 at 09:36

1 Answers1

4

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();
Ralf Bönning
  • 14,515
  • 5
  • 49
  • 67
  • 2
    or `await (user.RelatedEntityCanBeNull?.ToListAsync() ?? Task.FromResult<...>(null));` to be more concise. – stop-cran Nov 01 '16 at 09:27
  • @stop-cran your decision let to escape manual null -check even when there is long chain properties in expression like this: user.First?.Second?... great – Ilya Loskutov Nov 01 '16 at 11:06