VB.NET String.Empty ExampleUse the String.Empty property. The empty string has length of zero but is not null.
Empty. An empty string has length 0. It is not null. We can specify in VB.NET an empty string with "" but the String.Empty property is easier to read. It may be better for code.
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: We use the IsNullOrEmpty method. This method correctly detects the empty string.String.IsNullOrEmpty
Length: Finally we access the Length property of the string. This returns, as expected, the value 0.String Length
VB.NET program that uses String.Empty
' Assign a string to String.Empty.
Dim value As String = String.Empty
' It equals an empty literal.
If value = "" Then
' It is detected by IsNullOrEmpty.
If String.IsNullOrEmpty(value) Then
' It has length 0.
There is no discernible
difference between using String.Empty and an empty literal. The main difference comes from the appearance, and readability, of code.
Tip: Passing String.Empty to a Function call is often more readable. But this comes down to your preference.
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.Shared
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.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to firstname.lastname@example.org.