Mystery of Not Operator in VB.Net

(Not 2) = -3.

Strange!

Read below.

In VB.Net, non-zero integer is evaluated as True and an integer whose value is zero is evaluated as False. This is known fact since earliest version of Visual Basic. And this is also supported by VB.Net.

Now consider following code:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim x As Integer = 2    'non zero integer is so x = True
    If Not x Then   'not True i.e. False
        Response.Write("X is False and the value of x is: " & Not x)
    Else
        Response.Write("True")
    End If
End Sub

Now there are two questions:

  1. What will be printed on the page: value of x or True.
  2. If value of x will be printed, what will be the value of x?

When I run the page, It printed

X is False and the value of x is: -3

which is strange, isn't it? I initialized x with 2. Since this is a non-zero integer, it should be True. So 'Not x' should be evaluated as False in the if condition and else part should be executed. This is supposed to print "True" on the page. But this is not the case.

The Mystery of Not

Investigating the issue, I found that NOT was a bit-wise operator in classical Visual Basic. It exhibits the same behavior in VB.Net. SO considering the bit-wise calculations,

2 in Binary is 0000 0010.

Not 2 will reverse the bit-pattern making it 1111 1101. Considering the last bit is a sign bit, 1111 1101 is -3 in decimal.

So the if condition now becomes

If Not x Then  
=> If -3 Then 
=> If True (since -3 is non-zero integer, this is True)

Hence it evaluated the If condition as true and printed the value of x as -3.

This is strange but true.

Download source code for this post (4KB zip).

kick it on DotNetKicks.com

Published Tuesday, February 3, 2009 2:59 PM by Yanesh Tyagi
Filed under: ,

Comments

# re: Mystery of Not Operator in VB.Net

Tuesday, February 3, 2009 9:28 AM by Dejan

Hi Yanesh, interesting article. But I don't understand why you consider this behavior of the NOT operator strange after you've explained clearly what and why it does it. To me at least (now) it makes sense that doing NOT on an Integer should do the bitwise operation first and then evaluate the expression into a boolean.

Cheers

# re: Mystery of Not Operator in VB.Net

Tuesday, March 27, 2012 10:07 PM by John

Here i was in a day-dream why i implemented the NOT (integer) form and came acrossed this and reminded myself what kind of stupor i was in back in the days.  Albeti i need the bit-wise transform but damn i need to get more of a life ;)

Thanx for reminding me.

# re: Mystery of Not Operator in VB.Net

Thursday, August 16, 2012 5:49 AM by Nick Roberts

It would surely be an improvement to use different names for the logical and bitwise operators. I think Not, And, Or, and Xor should operate exclusively on Boolean expressions and there should be functions Bitwise_Not(X), Bitwise_And, etc. for the bitwise operations on integers.