tags:

views:

877

answers:

4

Hi all. After two years of C#, I'm now back to VB.net because of my current job. In C#, I can do a short hand testing for null or false value on a string variable like this:

if(!String.IsNullOrEmpty(blah))
{
   ...code goes here
}

however I'm a little confused about how to do this in VB.net.

if Not String.IsNullOrEmpty(blah) then
   ...code goes here
end if

Does the above statement mean if the string is not null or empty? Is the Not keyword operate like the C#'s ! operator?

+6  A: 

Yes they are the same

Ruben
They act the same way, but they're definitely not the same. 'Not' in VB is overloaded to represent both logical negation and bitwise complement.
RoadWarrior
Thanks, I did not know that. I have not used bitwise complement operators in vb.net or C#
Ruben
A: 

Seconded. They work identically. Both reverse the logical meaning of the expression following the !/not operator.

Scott Mayfield
They act in the same way, but they're definitely not the same. 'Not' in VB is overloaded to represent both logical negation and bitwise complement.
RoadWarrior
+3  A: 

Not is exactly like ! (in the context of Boolean. See RoadWarrior's remark for its semantics as one's complement in bit arithmetic). There's a special case in combination with the Is operator to test for reference equality:

If Not x Is Nothing Then ' … '
' is the same as '
If x IsNot Nothing Then ' … '

is equivalent to C#'s

if (x != null) // or, rather, to be precise:
if (object.ReferenceEquals(x, null))

Here, usage of IsNot is preferred. Unfortunately, it doesn't work for TypeOf tests.

Konrad Rudolph
+1  A: 

In the context you show, the VB Not keyword is indeed the equivalent of the C# ! operator. But note that the VB Not keyword is actually overloaded to represent 2 C# equivalents:

  • logical negation: !
  • bitwise complement: ~

For example, the following 2 lines are equivalent:

C#: useThis &= ~doNotUse; 
VB: useThis = useThis And (Not doNotUse)
RoadWarrior