An empty string
has length 0. It is not Nothing. We can specify in VB.NET an empty string
with "" but the String.Empty
property is easier to read.
With IsNullOrEmpty
, we can test to see if a string
is either Nothing or has length 0. The 2 checks often come together, and the helper Shared function makes code clearer.
In this example, we introduce a string
variable called "value." We assign it to the String.Empty
property. Then we test it against "": this check evaluates to true.
IsNullOrEmpty
function. This function correctly detects the empty string
.Length
property of the string
. We print the value 0 to the console.Module Module1 Sub Main() ' Assign a string to String.Empty. Dim value As String = String.Empty ' It equals an empty literal. If value = "" Then Console.WriteLine(1) End If ' It is detected by IsNullOrEmpty. If String.IsNullOrEmpty(value) Then Console.WriteLine(2) End If ' It has length 0. Console.WriteLine(value.Length) End Sub End Module1 2 0
String.Empty
is a shared property. It is not a constant, so it has a tiny difference with an empty literal. A load must occur to read it.
IsNullOrWhiteSpace
A string
with only whitespace is not empty. But in some programs we might want to test for whitespace-only or null
strings. IsNullOrWhiteSpace
helps here.
Empty is a handy property to know about: it can make some code more self-documenting. The empty literal may be more mysterious. String.Empty
clearly indicates its contents.