I would like to differentiate between NULL and "".
How do I determine with an if statement if a String is NULL or ""?
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
Dim s as String = Nothing: Return s = "" will return true. Check my answer.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,"" = Nothingis 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 "").
"" 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
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
"" and Nothing how?
str Is Nothingversusstr = "", 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.