VB.Net Logical Operators - Boolean vs Bitwise

Tuesday, February 12, 2008 by Greg Berlin

I've just spent the better part of the last hour scratching my head over something so stupidly simple that its resulted in a sore head (due to the obligatory banging of it against my desk numerous times in frustration at the resolution)...

Basically, this is what caught me out... it seems VB.Net is a little quirky when it comes to handling If.. Then conditions. 

One would think that the following statement:

If myPickupBooking.Type = (EBookingType.StorePickUp Or EBookingType.StoreDropoff) Then ...

would  equate to the same as this statement:

If (myPickupBooking.Type = EBookingType.StorePickUp) Or (myPickupBooking.Type = EBookingType.StoreDropoff) Then ...

but this is not the case.  As it turns out, the first statement failed when the booking type was StorePickup... but the second statement passes. 

This has reaffirmed my suspicion that VB is really a language for dummies that have to spell e.v.e.r.y.t.h.i.n.g. o.u.t. a.s. v.e.r.b.o.s.e.l.y. a.s. i.s. h.u.m.a.n.l.y. p.o.s.s.i.b.l.e.  AAARRRGGGHHHHH

Okay, now that this little rant is out of the way, i'll get back to some real work.

UPDATE:  On further experimentation, i found that the following statement...

Dimhello As String = "hello"
If hello = ("hello" Or "goodbye") Then 
 
MsgBox(hello)
End If

... throws an Invalid Cast Exception:

Conversion from string "Hello" to type 'Double' is not valid.

This is because the Or operator compares either 2 boolean values (True or False), or integers that are evaluated Bitwise.  If you mix the 2, VB.Net will treat the Boolean value as though it were an Integer.  Hence the invalid cast exception above.

For more info about this, including some delving into the geekiness of converting values to bits, see the following:

 

1 comment(s) for “VB.Net Logical Operators - Boolean vs Bitwise”

  1. Gravatar of Jon
    Jon Says:
    Of the languages I know: c++, java, vb, c#, javascript, LISP, and pascal, none of them would allow the statement that you described. If vb is a language for dummies, it appears that you have chosen your language wisely.