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

前端 未结 10 1606
情话喂你
情话喂你 2021-01-30 19:41

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 no

相关标签:
10条回答
  • 2021-01-30 20:01

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

    0 讨论(0)
  • 2021-01-30 20:02

    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
    }
    
    0 讨论(0)
  • 2021-01-30 20:09
    bool value;
    if(rawValue is bool)
      value = (bool)rawValue;
    else {
      // something is not right...
    
    0 讨论(0)
  • 2021-01-30 20:19

    You can also try Convert.ToBoolean(rowValue);

    0 讨论(0)
  • 2021-01-30 20:21

    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.

    0 讨论(0)
  • 2021-01-30 20:22

    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)

    0 讨论(0)
提交回复
热议问题