Comparing integers using AND in If statements

It may seem silly, but I was stuck and I had no luck on the Internet for this to happen. I have a method that I want to check to make sure that both numbers entered are positive:

Public Function BothPositive(ByVal num1 As Integer, ByVal num2 As Integer) As Boolean If (num1 And num2) > 0 Then Return True Else Return False End If End Function 

Now, if I were to enter some numbers in

  • BothPositive (1,1) = True
  • BothPositive (1,2) = False
  • BothPositive (-10, 10) = True

Why is this? What happens to the order of operations in the comparison statement, or what does the AND try to compare with? I do not understand why this will not work.

EDIT: I understand how to work, but my question is - why is this happening? I want to know what happens, what causes it.

+4
source share
3 answers

Vb.Net And introduces a bitwise operator, so here you are creating a bitwise And from num1 and num2 and comparing this value to 0. What you want is to compare all the values ​​separately from 0. try the following

 If (num1 > 0) AndAlso (num2 > 0) Then 

Note the use of AndAlso here instead of the usual old And . AndAlso is a Boolean bitwise operator and also a short circuit. You almost always prefer it over And

+6
source

And it is a logical operation and will not work with integers as you expect (it performs bitwise or). You should write this as If num1 >0 And num2 > 0 Then ...

+2
source
 Public Function BothPositive(ByVal num1 As Integer, ByVal num2 As Integer) As Boolean If (num1 > 0 AND num2 > 0) Then Return True Else Return False End If End Function 
+1
source

All Articles