A hacked Boolean

reposted to fix the missing StructLayout and FieldOffset attributes


In VB.NET, And and Or are bitwise operations. They do accept Boolean operands, but the operation is still bitwise. To see this, I will show you a hacked Boolean.
The following structure allows us to manipulate the value stored inside a Boolean (hence the *hack* 🙂


<StructLayout(LayoutKind.Explicit)>_
Public Structure HackedBoolean
   <FieldOffset(0)>Public value As Int32
   <FieldOffset(0)>Public bool As Boolean


   Public Function GetBool(ByVal seed As Int32) As Boolean
      Me.value = seed
      Return Me.bool
   End Function
End Structure


You can then test this in code such as :


Dim operand1 As Boolean = HackedBoolean.GetBool(1)
Dim operand2 As Boolean = HackedBoolean.GetBool(2)


So at this point we have operand1 as a Boolean containing the value 1 and operand2 as a Boolean containing the value 2. Since in both cases, the value is non zero, by definition of a Boolean being bi-state only, the value of the Boolean is non zero thus non False. Some folk might say for the value 2 the Boolean is indeterminate, and it can behave that way with a bad compiler, or an immature compiler.


As a side note, in Vb.NET 2002 there were some issues when you compared a Boolean to the value True if it’s internal value was not 1, so operand2 would have not been false and not been True. In Vb.NET 2003 however, the compiler detects tests for equal to True and just checks if the value is non zero on the stack, which is more efficient and less error prone than doing a comparison with a value such as 1 (this is what it did in 2002).


So testing code in VB.NET 2003, you will get some interesting results:


Dim result As Boolean


result = operand1  ‘ result is True
result = operand2  ‘ result is True


result = operand1 = True  ‘ result is True
result = operand2 = True  ‘ result is True


result = operand1 = operand 2 ‘ result is False !!!



Now let’s look at the And operator :


result = operand1 And operand2


Guess what result is from the above code. If you guessed False, you’d be right. The reason is, the And operator does a bitwise and, which is bitwise and of 2 And 1, which is 0.


Now let’s try AndAlso:


result = operand1 AndAlso operand2


This time the result is True. This is because AndAlso is a branching construct based on the operands value on the stack not being zero.