1

I would like to differentiate between NULL and "".

How do I determine with an if statement if a String is NULL or ""?

3
  • Pretty valid question, not sure why down-voted...? Commented Apr 23, 2016 at 14:20
  • 1
    str Is Nothing versus str = "", there are plenty of questions/answers on SO related to the two. The only snag is that you need to do the nothing check before the = check to distinguish the two. Commented Apr 23, 2016 at 14:22
  • 3
    No it's not a valid question because it shows of lack of research. Also you have two questions. Commented Apr 23, 2016 at 14:24

5 Answers 5

7

Nothing is when the string variable has no instance it refers to at all while "" is when the string variable has something it refers to and it is an empty string.

To distinguish, you could put the following conditions:

Dim s As String

If s Is Nothing Then 'It means it is Nothing

End If

If s = "" Then 'It means it points to some instance whose value is empty string

End If

VB.Net also has String.Empty which is equivalent to "":

If s = String.Empty Then

End If
Sign up to request clarification or add additional context in comments.

1 Comment

Your answer is incomplete because Dim s as String = Nothing: Return s = "" will return true. Check my answer.
4

The accepted answer and the others are all partially wrong because they do not address a crucial point of empty strings in VB. According to the documentation:

For strings in Visual Basic, the empty string equals Nothing. Therefore, "" = Nothing is true.

This means that MyString = String.Empty will be true when MyString Is Nothing is also true. So you definitely want to test against Nothing before testing against String.Empty (or "").

Comments

2

"" is just an empty string, but it is still initialized and has an allocated position in the memory as a string with no characters.

Null or Nothing is a string that has not been initialized or defined, which means that there is no memory is allocated for this, thus the string technically doesn't exist.

To check if a string is null you'd do:

If str Is Nothing Then

To check if a string is empty you could do:

If str = "" Then

or:

If str.Length = 0 Then

However, to check if it's either null or empty, you get use of the String.IsNullOrEmpty() method:

If String.IsNullOrEmpty(str) Then

Comments

1

you can get dbnulll error if string come from database

you can determine it with

isdbnull(str)

Comments

0

Pass your string variable into this function to test for both:

String.IsNullOrEmpty(s) 

You can test for null like this:

s Is Nothing

You can test if it is an empty string like this:

s = String.Empty

1 Comment

And this distinguishes between "" and Nothing how?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.