1

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?

  • 1
    If you know it is a `boolean`, you should be able to just cast it: `var yourobj = (bool)valuefromreader;` – dub stylee Jul 24 '15 at 19:30
  • For some reason that didn't seem to work, but I guess it does. I think I was trying to convert it to a string at the same time. thanks –  Jul 24 '15 at 19:31
  • nevermind. I get an invalid cast when I try to cast it like `var obj = (bool)reader["field"]` –  Jul 24 '15 at 19:33

6 Answers6

4

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?;
Will Custode
  • 4,576
  • 3
  • 26
  • 51
2

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

Alyssa Haroldsen
  • 3,652
  • 1
  • 20
  • 35
  • I thought this would work and is what I first tried, but I do need a `bool`, thanks though –  Jul 24 '15 at 19:39
1

Like this:

bool? val = YourValue as bool?;
if (val != null)
{
   ....
}
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
1

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;

Martin_W
  • 1,582
  • 1
  • 19
  • 24
0

Try converting it.

var boolValue = (bool)yourObject;
lem2802
  • 1,152
  • 7
  • 18
0

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.

Community
  • 1
  • 1
Matt Martin
  • 807
  • 2
  • 8
  • 15