MATH000
MATH000

Reputation: 1103

Visual Basic .NET Empty/Null String difference?

I would like to differentiate between NULL and "".

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

Upvotes: 1

Views: 13360

Answers (5)

Ama
Ama

Reputation: 1565

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 "").

Upvotes: 3

Suleyman DOGAN
Suleyman DOGAN

Reputation: 185

you can get dbnulll error if string come from database

you can determine it with

isdbnull(str)

Upvotes: 1

Visual Vincent
Visual Vincent

Reputation: 18310

"" 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

Upvotes: 2

Ian
Ian

Reputation: 30813

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

Upvotes: 7

Nate Anderson
Nate Anderson

Reputation: 690

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

Upvotes: 0

Related Questions