Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not keyword vs = False when checking for false boolean condition

Tags:

vb.net

When I'm using an If statement and I want to check if a boolean is false should I use the "Not" keyword or just = false, like so

If (Not myboolean) then 

vs

If (myboolean = False) then

Which is better practice and more readable?

like image 541
Nathan W Avatar asked Oct 29 '08 03:10

Nathan W


People also ask

Which is the wrong way for checking that a variable is not true?

Similarly, we can check if a variable is not True using one of the following methods: if variable != True: ("bad") if variable is not True: ("bad")

How do you check if a Boolean is False in Python?

The Python Boolean type is one of Python's built-in data types. It's used to represent the truth value of an expression. For example, the expression 1 <= 2 is True , while the expression 0 == 1 is False .

What is False in Boolean?

FALSE is a variable of reference type Boolean . Its value is reference to the object of type Boolean which internal boolean state is false . Save this answer.

What is the purpose of the NOT operator?

The NOT operator is used in most programming languages which support logical and comparison operators. In the programming world, it is mainly used to control the flow of the program. It is used in construction of logical statements and in supporting bitwise negation.


2 Answers

It does not make any difference as long you are dealing with VB only, however if you happen to use C functions such as the Win32 API, definitely do not use "NOT" just "==False" when testing for false, but when testing for true do not use "==True" instead use "if(function())".

The reason for that is the difference between C and VB in how boolean is defined.

  1. In C true == 1 while in VB true == -1 (therefore you should not compare the output of a C function to true, as you are trying to compare -1 to 1)

  2. Not in Vb is a bitwise NOT (equal to C's ~ operator not the ! operator), and thus it negates each bit, and as a result negating 1 (true in C) will result in a non zero value which is true, NOT only works on VB true which is -1 (which in bit format is all one's according to the two's complement rule [111111111]) and negating all bits [0000000000] equals zero.

For a better understanding see my answer on Is there a VB.net equivalent for C#'s ! operator?

like image 61
yoel halb Avatar answered Oct 07 '22 01:10

yoel halb


Definitely, use "Not". And for the alternately, use "If (myboolean)" instead of "If (myboolean = true)"

The works best if you give the boolean a readable name:

 if (node.HasChildren)
like image 28
James Curran Avatar answered Oct 07 '22 00:10

James Curran