String concatenation uses the + operator instead of &
ID |
vbnet.maintainability.operator_concatenate_strings |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
String Handling |
Language |
VB.NET |
Description
Reports uses of the + operator where one of the operands is a string literal, so the
intent is string concatenation rather than arithmetic addition.
Rationale
In Visual Basic + is overloaded: it adds numbers and it concatenates strings, and which one
it does depends on the run-time types of its operands. With Option Strict Off a String
that happens to hold digits is converted to a number, so "10" + value can silently produce
12 instead of "102", and a value that is not numeric raises an InvalidCastException at
run time instead of concatenating. Nothing is treated as 0 rather than as an empty string.
The & operator has a single meaning, converts both operands to String, and makes the
intent unambiguous to the next reader.
The following code illustrates the pattern detected by this rule:
Public Function BuildTitle(ByVal customer As String) As String
' FLAGGED: String concatenation uses the + operator instead of &
Return "Monthly report for " + customer
End Function
Remediation
Use the & concatenation operator (and &= for compound assignment) whenever the intent is
to join strings. Reserve + for arithmetic. For more than a few pieces prefer
String.Concat, String.Format, an interpolated string, or a StringBuilder.
' Before: + may add instead of concatenate
Return "Monthly report for " + customer
' After: & always concatenates
Return "Monthly report for " & customer