The bool? nullable type can contain three different values: true, false and null. As such, the cannot be used in conditionals such as with if, for, or while. For example, this code fails to compile with Compiler Error CS0266:
bool? b = null;
if (b) // Error CS0266.
{
} This is not allows because it is unclear what null means in the context of a conditional. Nullable Booleans can be cast to a bool explicitly in order to be used in a conditional, but if the object has a value if null, InvalidOperationException will be thrown. It is therefore important to check the HasValue property before casting to bool.
Nullable Booleans are similar to the Boolean variable type used in SQL. To ensure that the results produced by the & and | operators are consistent with SQL's three-valued Boolean type, the following predefined operators are provided:
bool? operator &(bool? x, bool? y)
bool? operator |(bool? x, bool? y)
The results of these operators are listed in the table below:
|
X
|
y
|
x&y
|
x|y
|
| True | true | True | true |
| True | false | False | true |
| True | null | Null | true |
| False | true | False | true |
| False | false | False | false |
| False | null | False | null |
| Null | true | Null | true |
| Null | false | False | null |
| Null | null | Null | null |