Empty-string test written as a comparison against "" or String.Empty
ID |
vbnet.performance.test_for_empty_strings_using_length |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
String Handling |
Language |
VB.NET |
Description
Reports a string tested for emptiness by comparing it with "" or String.Empty using =
or <>, instead of inspecting its length or calling String.IsNullOrEmpty.
Rationale
Visual Basic does not compile s = "" into a reference or ordinal check. It emits a call to
CompilerServices.Operators.CompareString, a full string comparison that honours
Option Compare - so with Option Compare Text the test becomes a culture-aware comparison.
Inspecting Length reads a field that the runtime already stores and returns as soon as it is
non-zero, which is why it is the documented way to test for an empty string. The comparison
also hides which of two different intents is meant: s = "" is True when s is Nothing,
because CompareString treats Nothing as an empty string, so a genuine "no value at all"
is silently folded into "empty".
The following code illustrates the pattern detected by this rule:
Public Function IsIncomplete(ByVal name As String, ByVal email As String) As Boolean
' FLAGGED: Empty-string test written as a comparison against "" or String.Empty
If name = "" AndAlso email = "" Then
Return True
End If
' FLAGGED: Empty-string test written as a comparison against "" or String.Empty
Return name = ""
End Function
Remediation
Use String.IsNullOrEmpty(s) when Nothing and "" should be treated alike - it is the
direct equivalent of the comparison and states the intent. When the string is known not to be
Nothing, test s.Length = 0 (or s.Length > 0 for the <> form). Use
String.IsNullOrWhiteSpace if blank input should count as empty too.
' Before: a full CompareString call, and Nothing silently counts as empty
If name = "" Then Return True
If comment <> String.Empty Then Process(comment)
' After
If String.IsNullOrEmpty(name) Then Return True
If comment.Length > 0 Then Process(comment)