Reputation:
I'm reading in data from a sqlite reader. It's returning an object
, most of them I know are boolean
. What's the best way to convert object
into a boolean
?
Upvotes: 1
Views: 6742
Reputation: 1787
If you must have a final bool
value, for C# 7.0 (introduced in 2017) and later, a compact syntax is:
bool myBool = (myObject as bool?) ?? false;
So this might be "best" from the standpoint of brevity. But code using the is
operator performs better (see here). In this case, the following may be preferred:
bool myBool = myObject is bool ? (bool)myObject : false;
Upvotes: 1
Reputation: 827
If you want case an object to a boolean type, you simply need to check if the object is
a bool, then cast it, like so:
if (someObject is bool)
{
bool someBool = (bool)someObject;
...
}
As a side note, it is not possible to use the as
operator on a non-reference type (because it cannot be null). This question may be a duplicate of this one.
Upvotes: 0
Reputation: 39956
Like this:
bool? val = YourValue as bool?;
if (val != null)
{
....
}
Upvotes: 1
Reputation: 4594
I would probably go through TryParse
. Otherwise you run the risk of throwing an exception. But it depends on how your system is written.
object x;
bool result = false;
if(bool.TryParse(string.Format("{0}", x), out result))
{
// do whatever
}
Alternatively you can do a direct cast:
bool result = (bool)x;
Or use the Convert
class:
bool result = Convert.ToBoolean(x);
Or you can use a Nullable<bool>
type:
var result = x as bool?;
Upvotes: 4
Reputation: 3731
In this case, you'll probably want the as operator. Keep in mind, your type would be a bool?
.
Upvotes: 2