I work with VBA and VB6 so I miss some things.
I notice in sample code that some folks use

if MyString <> "" then

and others use

if Not MyString = VBNullString

Is there a difference, and why?
Thank you in advance

Recommended Answers

All 6 Replies

In vb.net you can treat vbNullString as being equivalent to "" but they are not treated exactly the same. For example, in the following code

Dim s As String = ""

If s = vbNullString Then
    MsgBox("same")
End If

the message "same" will be displayed when run, however, if you put a breakpoint on the End If and open the Immediate window you can get the following results

?s = ""
True
?s = vbNullString
Unable to evaluate expression.

so obviously vb does not quite treat "" and vbNullString equivalently. If you want to know how this is handled in VBA or VB6 then post in that forum.

Here is another take on that.

I would use the length of string.
Works well in most languages.

would have been more realistic (timingwise) if they had compared

If StrTemp = vbNullString

with

If StrTemp = ""

Although I suspect programmers would achieve better results looking for other things to optimize.

What value does vbNullString represent?

All:
Thanks for taking the time to respond. Very enlightening.

Reverend Jim:
Thank you. I hadn't thought of doing that.
When I tried your example in my IDE, S always evaluated to "" in the locals window.
The msgbox always showed when equal values were compared, including LenB (S) = 0 vs vbNullString or ""
I also tried it with Not and with <>. What one would expect to be equal always displayed the msgbox
and S always evaluated to "".
I have no clue why the difference.

If I understand correctly, declaring strings in languages .Net and on, is done more precisely. I can see how the question might get more complicated.

Of course it may be that my Locals window doesn't know how to say vbNullString.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.