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