Επεξεργασία

Κοινή χρήση μέσω


Concatenation Operators in Visual Basic

Concatenation operators join multiple strings into a single string. There are two concatenation operators, + and &. Both carry out the basic concatenation operation, as the following example shows.

Dim x As String = "Mic" & "ro" & "soft"
Dim y As String = "Mic" + "ro" + "soft"
' The preceding statements set both x and y to "Microsoft".

These operators can also concatenate String variables, as the following example shows.

Dim a As String = "abc"
Dim d As String = "def"
Dim z As String = a & d
Dim w As String = a + d
' The preceding statements set both z and w to "abcdef".

Differences Between the Two Concatenation Operators

The + Operator has the primary purpose of adding two numbers. However, it can also concatenate numeric operands with string operands. The + operator has a complex set of rules that determine whether to add, concatenate, signal a compiler error, or throw a run-time InvalidCastException exception.

The & Operator is defined only for String operands, and it always widens its operands to String, regardless of the setting of Option Strict. The & operator is recommended for string concatenation because it is defined exclusively for strings and reduces your chances of generating an unintended conversion.

Performance: String and StringBuilder

If you do a significant number of manipulations on a string, such as concatenations, deletions, and replacements, your performance might profit from the StringBuilder class in the System.Text namespace. It takes an extra instruction to create and initialize a StringBuilder object, and another instruction to convert its final value to a String, but you might recover this time because StringBuilder can perform faster.

See also