简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM