What is the difference between vbNullString, String.Empty and ""? - vb.net

All of these
txtUsername.Text <> vbNullString
txtUsername.Text <> String.Empty
txtUsername.Text <> ""
seem to return the same result. So, what's the difference between vbNullString, String.Empty and ""?

What's the difference?
String.Empty and "" both represent a string of length zero.
Contrary to the documentation, which claims that vbNullString "[r]epresents a zero-length string", vbNullString is actually Nothing (null in C#, see Reference Source).
(Note that this only applies to VB.NET! The situation is different in VBA, see below for details.)
So how do I check if a string is null/Nothing or empty?
Contrary to what the other answer says, you do not need to use String.IsNullOrEmpty to check for Nothing or an empty string, since the = operator in Visual Basic treats Nothing and an empty string as equivalent. Thus, the idiomatic way to check for "null or empty string" in VB.NET is to simply use = "":
Dim s As String = Nothing
If s = "" Then Console.WriteLine("YES") ' Prints YES
Thus, Not String.IsNullOrEmpty(s), s <> "", s <> String.Empty and s <> vbNullString are all equivalent. I prefer the concise s <> "", but it's mainly a question of preference and style.
Does that mean that I can use an empty string and Nothing interchangeably?
In general: no. This equivalence of an empty string and Nothing is only true for VB.NET's built-in = and <> operators as well as most of the methods in the Microsoft.VisualBasic namespace (Len(...), Trim(...), ...). Once you go into pure .NET territory (for example, by using methods from the rest of the Base Class Library), Nothing and the empty string are treated differently:
Dim sNothing As String = Nothing
Dim sEmpty As String = ""
Console.WriteLine(sEmpty = sNothing) ' True
Console.WriteLine(sEmpty.Equals(sNothing)) ' False
Console.WriteLine(String.Equals(sEmpty, sNothing)) ' False
Console.WriteLine(Len(sEmpty)) ' 0
Console.WriteLine(Len(sNothing)) ' 0
Console.WriteLine(sEmpty.Length) ' 0
Console.WriteLine(sNothing.Length) ' throws a NullReferenceException
Why is vbNullString defined as Nothing instead of ""?
Backwards compatibility. In VBA (and "VB Classic"), vbNullString could be used to get a "null string reference"¹. Within VBA, vbNullString was treated like the empty string "", but when interacting with non-VB-code, vbNullString was mapped to the NULL pointer and "" was mapped to an empty string.
When using PInvoke in VB.NET, Nothing is mapped to the NULL pointer and "" is mapped to an empty string, so it makes sense to have the legacy constant vbNullString equal Nothing in VB.NET.
¹ which is completely different from VBA's Null and Empty, which are special Variant subtypes, and VBA's Nothing, which, in VBA, only applies to objects and not to strings.

vbNullString is a constant, more likely out of VB6, String.Empty and "" are the same, some say that there is a performance difference, but that is not true, it is your choice what you use.
To check whether a string is empty you can use If String.IsNullOrEmpty(String). The advantage is that it will also check for null, because string is a class and because of this a reference type.

If are going to insert values to MS-SQL database and if column doesn't allows null(Not null) then strValue=vbNullString will generate exception but strValue="" will insert blank spaces.

Related

Differences between "" and vbnullstring [duplicate]

All of these
txtUsername.Text <> vbNullString
txtUsername.Text <> String.Empty
txtUsername.Text <> ""
seem to return the same result. So, what's the difference between vbNullString, String.Empty and ""?
What's the difference?
String.Empty and "" both represent a string of length zero.
Contrary to the documentation, which claims that vbNullString "[r]epresents a zero-length string", vbNullString is actually Nothing (null in C#, see Reference Source).
(Note that this only applies to VB.NET! The situation is different in VBA, see below for details.)
So how do I check if a string is null/Nothing or empty?
Contrary to what the other answer says, you do not need to use String.IsNullOrEmpty to check for Nothing or an empty string, since the = operator in Visual Basic treats Nothing and an empty string as equivalent. Thus, the idiomatic way to check for "null or empty string" in VB.NET is to simply use = "":
Dim s As String = Nothing
If s = "" Then Console.WriteLine("YES") ' Prints YES
Thus, Not String.IsNullOrEmpty(s), s <> "", s <> String.Empty and s <> vbNullString are all equivalent. I prefer the concise s <> "", but it's mainly a question of preference and style.
Does that mean that I can use an empty string and Nothing interchangeably?
In general: no. This equivalence of an empty string and Nothing is only true for VB.NET's built-in = and <> operators as well as most of the methods in the Microsoft.VisualBasic namespace (Len(...), Trim(...), ...). Once you go into pure .NET territory (for example, by using methods from the rest of the Base Class Library), Nothing and the empty string are treated differently:
Dim sNothing As String = Nothing
Dim sEmpty As String = ""
Console.WriteLine(sEmpty = sNothing) ' True
Console.WriteLine(sEmpty.Equals(sNothing)) ' False
Console.WriteLine(String.Equals(sEmpty, sNothing)) ' False
Console.WriteLine(Len(sEmpty)) ' 0
Console.WriteLine(Len(sNothing)) ' 0
Console.WriteLine(sEmpty.Length) ' 0
Console.WriteLine(sNothing.Length) ' throws a NullReferenceException
Why is vbNullString defined as Nothing instead of ""?
Backwards compatibility. In VBA (and "VB Classic"), vbNullString could be used to get a "null string reference"¹. Within VBA, vbNullString was treated like the empty string "", but when interacting with non-VB-code, vbNullString was mapped to the NULL pointer and "" was mapped to an empty string.
When using PInvoke in VB.NET, Nothing is mapped to the NULL pointer and "" is mapped to an empty string, so it makes sense to have the legacy constant vbNullString equal Nothing in VB.NET.
¹ which is completely different from VBA's Null and Empty, which are special Variant subtypes, and VBA's Nothing, which, in VBA, only applies to objects and not to strings.
vbNullString is a constant, more likely out of VB6, String.Empty and "" are the same, some say that there is a performance difference, but that is not true, it is your choice what you use.
To check whether a string is empty you can use If String.IsNullOrEmpty(String). The advantage is that it will also check for null, because string is a class and because of this a reference type.
If are going to insert values to MS-SQL database and if column doesn't allows null(Not null) then strValue=vbNullString will generate exception but strValue="" will insert blank spaces.

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 ""?
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
"" 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
you can get dbnulll error if string come from database
you can determine it with
isdbnull(str)
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
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 "").

Passing a string to a database with ToUpper? VB.NET 2010

I'm trying to validate a textbox. If user enters all lower case characters then convert it to all upper case. So when its added to the database its all upper case. I need help with my function, I don't know if its a syntax error or something, here it is. I'm using VB.Net 2010
Public Function CheckLetters(ByVal strIn As String) As Boolean
Dim i As Integer
Dim strOne As String
For i = 0 To Len(strIn) - 1
strOne = strIn.Substring(i, 1).ToUpper
Select Case strOne
Case "A" To "Z"
Case Else
Return False
End Select
Next
Return True
End Function
How 'bout this:
Return Regex.IsMatch(strIn, "^[a-z]*$")
or this
Return strIn.All(Function(c) Char.IsLower(c))
There's no good reason for this method to be anything other than a one-liner. But if you really want to loop through the characters:
For Each c As Char In strIn
If Not Char.IsLower(c) Then Return False
Next c
Return True
Your code runs just fine here (VB does not require the brackets after ToUpper, but it's good for readability) - it accepts a string and returns True if that string only contains the characters "A" through "Z", false otherwise. The function doesn't convert anything - just returns that Boolean result.
If you want to actually convert the string to upper case, just use .ToUpper() on the string itself, e.g.
Dim MyString As String = "Contains some text"
MyString = MyString.ToUpper()
' Above would set MyString to "CONTAINS SOME TEXT"

Why doesn't If Not IsEmpty filter out empty strings?

What is wrong with my If condition?
If Not IsEmpty(Wrkgps_L3) And Not IsEmpty(Wrkgps_L4) Then
Wrkgps_L3L4 = Wrkgps_L3 & "," & Wrkgps_L4
End If
The Not condition doesn't seem to work. The code within the If statement gets executed even when both Wrkgps_L3 and Wrkgps_L4 are empty strings.
Update:
Wrkgps_L3 and Wrkgps_L4 are variables that contain results returned from a function. I noticed that IsEmpty(Wrkgps_L3) = False even though Wrkgps_L3 = "". I had to rewrite my code to
If (Wrkgps_L3 <> "") And (Wrkgps_L4 <> "") Then
In any case, I am still intrigued to know why IsEmpty doesn't work on variables with ""?
In Visual Basic, Empty and "" (an empty string) are two different things. Empty is the uninitialized state of a Variant variable, and IsEmpty tests whether a Variant variable has the Empty value:
Dim x As Variant
If IsEmpty(x) Then
Debug.Print "x is empty"
End If
As you've observed, you must compare against "" when checking whether a String variable contains an empty string.
If the variables are strings, you could also:
If Len(Wrkgps_L3) + Len(Wrkgps_L4) = 0 Then
' They're both empty string variables
Else
' One or the other contains at least one character
End If

Nothing = String.Empty (Why are these equal?)

Why does the first if statement evaluate to true? I know if I use "is" instead of "=" then it won't evaluate to true. If I replace String.Empty with "Foo" it doesn't evaluate to true. Both String.Empty and "Foo" have the same type of String, so why does one evaluate to true and the other doesn't?
//this evaluates to true
If Nothing = String.Empty Then
End If
//this evaluates to false
If Nothing = "Foo" Then
End If
Nothing in VB.net is the default value for a type. The language spec says in section 2.4.7:
Nothing is a special literal; it does not have a type and is convertible to all types in the type system, including type parameters. When converted to a particular type, it is the equivalent of the default value of that type.
So, when you test against String.Empty, Nothing is converted to a string, which has a length 0. The Is operator should be used for testing against Nothing, and String.Empty.Equals(Nothing) will also return false.
It's a special case of VB's = and <> operators.
The Language Specification states in Section 11.14:
When doing a string comparison, a null reference is equivalent to the string literal "".
If you are interested in further details, I have written an in-depth comparison of vbNullString, String.Empty, "" and Nothing in VB.NET here:
https://stackoverflow.com/a/34069187/87698
Related to this topic, if you use a string variable initialized with "nothing" to be assigned to the property "value" of a SqlParameter that parameter is ignored, not included in the command sent to the server, and a missing parameter error is thrown.
If you initialize that variable with string.empty everything goes fine.
//This doesn't work
Dim myString as String = nothing
mySqlCommand.Parameters.Add("#MyParameter", SqlDbType.Char).Value = myString
//This works
Dim myString as String = string.empty
mySqlCommand.Parameters.Add("#MyParameter", SqlDbType.Char).Value = myString
Try this:
Console.WriteLine("Is String.Empty equal to Nothing?: {0}", String.Empty.Equals(Nothing))
The = operator doesn't enforce equal types, whereas the .Equals() method of a string object does, as does the Is operator.