I’ve often seen code that tries to get a numeric bit (1, 0) value for a boolean.
I know of three ways you can do it:
- Manual condition checking
- Use the GetHashCode() method
- Use the built in .Net Convert class
All three approaches do the job however I find that using the Convert.ToByte(boolValue) makes the most sense from a readability stance.
The following examples mix it up a bit and accommodate a Nullable<bool>.
Let’s start with the scenario where true is 1 and false and null are 0.
bool? tVal = true;
bool? fVal = false;
bool? nVal = null;
// true = 1, false = 0, null = 0
Assert.AreEqual(1, tVal.HasValue && tVal.Value ? 1 : 0);
Assert.AreEqual(0, fVal.HasValue && fVal.Value ? 1 : 0);
Assert.AreEqual(0, nVal.HasValue && nVal.Value ? 1 : 0);
Assert.AreEqual(1, tVal.GetHashCode());
Assert.AreEqual(0, fVal.GetHashCode());
Assert.AreEqual(0, nVal.GetHashCode());
Assert.AreEqual(1, Convert.ToByte(tVal));
Assert.AreEqual(0, Convert.ToByte(fVal));
Assert.AreEqual(0, Convert.ToByte(nVal));
Now let’s mix it up a bit and say that a null value should represent a TRUE or 1 value by default.
i.e. true = 1, null = 1, false = 0,
bool? tVal = true;
bool? fVal = false;
bool? nVal = null;
Assert.AreEqual(1, !tVal.HasValue || tVal.Value ? 1 : 0);
Assert.AreEqual(0, !fVal.HasValue || fVal.Value ? 1 : 0);
Assert.AreEqual(1, !nVal.HasValue || nVal.Value ? 1 : 0);
Assert.AreEqual(1, (tVal ?? true).GetHashCode());
Assert.AreEqual(0, (fVal ?? true).GetHashCode());
Assert.AreEqual(1, (nVal ?? true).GetHashCode());
Assert.AreEqual(1, Convert.ToByte(tVal ?? true));
Assert.AreEqual(0, Convert.ToByte(fVal ?? true));
Assert.AreEqual(1, Convert.ToByte(nVal ?? true));
Is there an easier, better or another alternate way to do this?
I’d love to hear your thoughts?
November 24th, 2008 at 9:09 am #gerrod
It depends on why you’re doing the conversion.
If it’s simply to pass in to a byte field in the database, you can just pass it as a boolean and let the framework handle the conversion for you. Not sure how this works with a nullable bool and a NULL DB field, though…
But in general I think I’d go with the Convert.ToByte as well; that’s my usual fallback when there is no implicit (/explicit) cast operator defined.
November 24th, 2008 at 8:24 pm #Ben
Quite correct young man when dealing with a DB, however this scenario was not the impetus for such an article.
July 21st, 2009 at 7:07 pm #Igor
byte /*or int*/ v = 1;
bool b = Convert.ToBoolean(v);
November 3rd, 2009 at 3:02 am #GP
Here’s something I use-
bool boolvariable = args.Length > 0 ? int.TryParse(args[0], out outnum) ? Convert.ToBoolean(Convert.ToByte(args[0])) : Convert.ToBoolean(args[0]) : true;