String.Empty Example
This page was last reviewed on Feb 16, 2022.
Dot Net Perls
Empty. 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.
Detail We use the IsNullOrEmpty function. This function correctly detects the empty string.
Detail Finally we access the Length property of the string. We print the value 0 to the console.
String Length
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 Module
1 2 0
Shared. 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.
But For almost all programs, no difference is going to be detected. For maximum performance, I recommend directly using the empty literal.
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.
A review. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 16, 2022 (image).
© 2007-2024 Sam Allen.