I’m trying to retrieve a boolean from a hashtable… my code looks something like this:
Hashtable h = new Hastable();
...
h["foo"] = true;
...
object o = h["foo"];
if( o == null ) { return false; }
if( o.GetType() != typeof(bool) ) { return false; }
return (bool)o;
In contrast I use something like this for objects
return h["foo"] as MyObject;
Is there a nicer solution for booleans?
Well, if a Hashtable must be used (or the data is typed
objectfor other reasons), consider:And:
That is,
bool?(orNullable<bool>) is happy being anastarget (becausenullis a valid value for nullable-types) and the result is easily coalesced out (with??) tobool.Happy coding.