Why use a null conditional operator when setting a bool value without using a nullable bool?

I have the following line of code:

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

Exists on the left is a property of the User class. Is its type equal to bool , not bool? . The Exists method on the right is an API method to check if a given object exists in the repository. It returns a 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, the entire right side will simply return null, which cannot be assigned to the bool type, but the compiler seems to handle it well. Is this the default value false?

+5
source share
1 answer

The problem is the wait. The nullable value occurs before waiting, so it likes await (this.repository?.Exists(id)) , which when this.repository is null, turns into await (null?.Exists(id)) , which turns into await (null) , which crashes .. cannot get into Task<bool> and make it Task<bool?> .

This way you will either get the correct boolean value or an exception.

+7
source

Source: https://habr.com/ru/post/1259619/


All Articles