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

前端 未结 10 1703
情话喂你
情话喂你 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: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.

提交回复
热议问题