Concatenation Operators in Visual Basic
Updated: July 20, 2015
For the latest documentation on Visual Studio 2017, see Visual Studio 2017 Documentation.
Concatenation operators join multiple strings into a single string. There are two concatenation operators,
&. 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".
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.
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.