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

C#.NetCasting

C# Problem Overview


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?

C# Solutions


Solution 1 - 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.

Solution 2 - C#

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)

Solution 3 - C#

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

Solution 4 - C#

You haven't defined what you want to have happen if rawValue is not convertible to bool. Common choices are to return false, null, or throw an exception. There's also the possibility of the string representation of rawValue to be convertible to a bool, such as Yes/No, True/False, 1/0, etc.

I would use bool.TryParse to do the conversion. This will succeed if rawValue is a bool or its string value is "True" or "False".

bool result;
if (!bool.TryParse(rawValue as string, out result))
{
    // you need to decide what to do in this case
}

Solution 5 - C#

You can cast it to a bool? with the as keyword and check the HasValue property.

Solution 6 - C#

With C# 9 you can also simplify to:

if(rawValue is true)
{
    //do stuff
}

Solution 7 - C#

Providing you don't actually need to keep a reference to the rawValue, here's a one-liner using the GetValueOrDefault() method of the Nullable<T> structure:

bool value = (map.GetValue(key) as bool?).GetValueOrDefault();

You can also specify a default value using the method overload GetValueOrDefault(T).

Solution 8 - C#

I used this check before doing something with object

if(myCrazyObject.GetType().Equals(typeof(bool)))
{
   //do smt with it
}

Solution 9 - C#

If the goal is to have true only if the raw object is boolean 'true' then one-liner (rawValue as bool?)?? false will do:

object rawValue=null
(rawValue as bool?)?? false
false
rawValue="some string"
(rawValue as bool?)?? false
false
rawValue=true
(rawValue as bool?)?? false
true
rawValue="true"
(rawValue as bool?)?? false
false
rawValue=false
(rawValue as bool?)?? false
false
rawValue=""
(rawValue as bool?)?? false
false
rawValue=1
(rawValue as bool?)?? false
false
rawValue=new Dictionary<string,string>()
(rawValue as bool?)?? false
false`

Solution 10 - C#

bool value = (rawValue is null) ? false : (bool)rawValue.value;

if rawValue is null then value will be false, otherwise value will receive the correct boolean value.

Solution 11 - C#

You can also try Convert.ToBoolean(rowValue);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaniel FortunovView Question on Stackoverflow
Solution 1 - C#Jon SkeetView Answer on Stackoverflow
Solution 2 - C#SLaksView Answer on Stackoverflow
Solution 3 - C#WebleeuwView Answer on Stackoverflow
Solution 4 - C#Jamie IdeView Answer on Stackoverflow
Solution 5 - C#Klaus Byskov PedersenView Answer on Stackoverflow
Solution 6 - C#FalkView Answer on Stackoverflow
Solution 7 - C#Nick W.View Answer on Stackoverflow
Solution 8 - C#Project MayhemView Answer on Stackoverflow
Solution 9 - C#dmitryView Answer on Stackoverflow
Solution 10 - C#Michael HutterView Answer on Stackoverflow
Solution 11 - C#user3934664View Answer on Stackoverflow