How to: Safely Cast from bool? to bool (C# Programming Guide)

The bool? nullable type can contain three different values: true, false, and null. Therefore, the bool? type cannot be used in conditionals such as with if, for, or while. For example, the following code causes a compiler error.

bool? b = null;
if (b) // Error CS0266.
{
}

This is not allowed because it is unclear what null means in the context of a conditional. To use a bool? in a conditional statement, first check its HasValue property to ensure that its value is not null, and then cast it to bool. For more information, see bool. If you perform the cast on a bool? with a value of null, a InvalidOperationException will be thrown in the conditional test. The following example shows one way to safely cast from bool? to bool:

Example

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

See Also

Reference

Literal Keywords (C# Reference)

Nullable Types (C# Programming Guide)

Concepts

C# Programming Guide