user5153737
user5153737

Reputation:

C# Convert a generic object into a boolean

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

Answers (6)

Martin_W
Martin_W

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

Matt Martin
Matt Martin

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

lem2802
lem2802

Reputation: 1162

Try converting it.

var boolValue = (bool)yourObject;

Upvotes: 0

Salah Akbari
Salah Akbari

Reputation: 39956

Like this:

bool? val = YourValue as bool?;
if (val != null)
{
   ....
}

Upvotes: 1

Will Custode
Will Custode

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

Alyssa Haroldsen
Alyssa Haroldsen

Reputation: 3731

In this case, you'll probably want the as operator. Keep in mind, your type would be a bool?.

Upvotes: 2

Related Questions