Drew Drew - 1 year ago 61
C# Question

Why can the null conditional operator be used when setting the value of a bool without using a nullable bool?

I have the following line of code:

user.Exists = await this.repository?.Exists(id);

on the left hand side is a property of the
class. Its type is just
, not
. The
method on the right hand side is an API method to check if a given entity exists in the repository. It returns
. I want to check if the repository is null first so I use the null conditional operator. I thought that if the repository is null then the whole right hand side would just return null, which cannot be assigned to a
type, but the compiler seems to be fine with it. Does it just default to a false value somehow?

Answer Source

The problem is the await. The nullable is happening before the await, so it's like await (this.repository?.Exists(id)), which, when this.repository is null, turns into await (null?.Exists(id)), which turns into await (null), which crashes. The ?. isn't capable of reaching into the Task<bool> and making it Task<bool?>.

So you will either get the proper boolean, or an Exception.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download