(Not 2) = -3.
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
- What will be printed on the page: value of x or True.
- 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).