Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

casting

I am extracting a bool value from a (non-generic, heterogeneous) collection.

The as operator may only be used with reference types, so it is not possible to do use as to try a safe-cast to bool:

// This does not work: "The as operator must be used with a reference type ('bool' is a value type)"
object rawValue = map.GetValue(key);
bool value = rawValue as bool;

Is there something similar that can be done to safely cast an object to a value type without possibility of an InvalidCastException if, for whatever reason, the value is not a boolean?

like image 954
Daniel Fortunov Avatar asked Dec 29 '09 14:12

Daniel Fortunov


People also ask

How do I cast a boolean in C#?

The Convert. ToBoolean() method converts an integer value to a boolean value in C#. In C#, the integer value 0 is equivalent to false in boolean, and the integer value 1 is equivalent to true in boolean.

What does bool do C sharp?

The bool type keyword is an alias for the . NET System. Boolean structure type that represents a Boolean value, which can be either true or false . To perform logical operations with values of the bool type, use Boolean logical operators.


2 Answers

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 image 71
Jon Skeet Avatar answered Oct 16 '22 18:10

Jon Skeet


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)

like image 20
SLaks Avatar answered Oct 16 '22 17:10

SLaks