Is there a nice way to get a boolean from a Hashtable?

c#

Solution

Well, if a Hashtable must be used (or the data is typed `object` for other reasons), consider:

object obj = true;
bool b = (obj as bool?) ?? false;
// b -> true

And:

object obj = "hello";
bool b = (obj as bool?) ?? false;
// b -> false

That is, `bool?` (or `Nullable<bool>`) is happy being an `as` target (because `null` is a valid value for nullable-types) and the result is easily coalesced out (with `??`) to `bool`.

Happy coding.

Problem

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?

Original source