Search code examples
c#booleannullablenull-conditional-operator

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

Exists on the left hand side is a property of the User class. Its type is just bool, not bool?. The Exists method on the right hand side is an API method to check if a given entity exists in the repository. It returns Task<bool>. 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 bool type, but the compiler seems to be fine with it. Does it just default to a false value somehow?


Solution

  • 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.