How do I safely cast a System.Object to a `bool` in C#?

There are two options... with slightly surprising performance:

  • Redundant checking:

    if (rawValue is bool)
    {
        bool x = (bool) rawValue;
        ...
    }
    
  • Using a nullable type:

    bool? x = rawValue as bool?;
    if (x != null)
    {
        ... // use x.Value
    }
    

The surprising part is that the performance of the second form is much worse than the first.

In C# 7, you can use pattern matching for this:

if (rawValue is bool value)
{
    // Use value here
}

Note that you still end up with value in scope (but not definitely assigned) after the if statement.


Like this:

if (rawValue is bool) {
    bool value = (bool)rawValue;
    //Do something
} else {
    //It's not a bool
}

Unlike reference types, there's no fast way to try to cast to a value type without two casts. (Or a catch block, which would be worse)


bool value;
if(rawValue is bool)
  value = (bool)rawValue;
else {
  // something is not right...