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

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

提交回复
热议问题