String
IsNullOrEmpty
A String
sometimes has no valid characters. The reference itself may be Nothing. And if a String
does exist, it may be empty or have only whitespace characters.
These situations are detected with String.IsNullOrEmpty
and IsNullOrWhiteSpace
. We often use these functions in an If
-Then statement.
IsNullOrEmpty
Here we use the String
IsNullOrEmpty
Function. This Function returns a Boolean
. It checks the String
argument against the Nothing constant. And it checks its Length
as well.
String
reference is Nothing or the Length
is zero it returns True. Otherwise it returns False.Module Module1 Sub Main() ' Test a Nothing String. Dim test1 As String = Nothing Dim result1 As Boolean = String.IsNullOrEmpty(test1) Console.WriteLine(result1) ' Test an empty String. Dim test2 As String = "" If (String.IsNullOrEmpty(test2)) Then Console.WriteLine("Is empty") End If End Sub End ModuleTrue Is empty
IsNullOrWhiteSpace
This program uses String.IsNullOrWhiteSpace
. This Function checks also for the Nothing reference. But it checks instead for whitespace, not just an empty String
.
String.IsNullOrWhiteSpace
will return True if any of these conditions matches.Module Module1 Sub Main() ' Test a Nothing String. Dim test1 As String = Nothing Dim test2 As String = " " If String.IsNullOrWhiteSpace(test1) Then Console.WriteLine(1) End If If String.IsNullOrWhiteSpace(test2) Then Console.WriteLine(2) End If Dim test3 As String = "Sam" If String.IsNullOrWhiteSpace(test3) Then Console.WriteLine(3) ' Not reached. End If End Sub End Module1 2
IsNullOrEmpty
Internally, we find String
IsNullOrEmpty
is implemented in a straightforward way. It checks the String
against null
(Nothing) and checks the Length
against zero.
IsNullOrEmpty
has little or no performance impact. It does the minimal number of checks to perform its purpose.Length
or against Nothing, it would be faster and clearer to instead do those checks alone.IsNullOrWhiteSpace
String
IsNullOrWhiteSpace
does more work when String
data does exist. It scans over every character in the String
to see if every character is whitespace.
char
-checking loop is not needed, IsNullOrEmpty
would perform faster in a program.IsNullOrEmpty
is similar to IsNullOrWhiteSpace
. IsNullOrWhiteSpace
checks the entire String
for whitespace. If the string
contains only whitespace, the Function returns True.