Bool? The data type that can be null can contain three different values: True, false, and null. So bool? Type cannot be used in conditional statements, such as if, for, or while. For example, this Code cannot be compiled and a compiler error cs0266 will be reported:
bool? b = null;
if (b) // Error CS0266.
{
}
This is not allowed, because the meaning of null in the context of the condition is unclear. To use bool? In a condition statement ?, First check its hasvalue attribute to ensure that its value is not null, and then forcibly convert it to bool. For more information, see bool. If the bool of a null value is used? If a forced conversion is executed, invalidoperationexception is thrown in the condition test. The following example demonstrates a kind? Safely cast to bool:
bool? test = null; ...// Other code that may or may not // give a value to test. if(!test.HasValue) //check for a value { // Assume that IsInitialized // returns either true or false. test = IsInitialized(); } if((bool)test) //now this cast is safe { // Do something. }
From
How: From bool? Securely forcibly convert to bool (C # programming guide)