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
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`
You can also simply do, if it fits:
if(rawValue is true)
{
//do stuff
}
You can cast it to a bool? with the as keyword and check the HasValue property.
I used this check before doing something with object
if(myCrazyObject.GetType().Equals(typeof(bool)))
{
//do smt with it
}