Concatenation Operators

Concatenation is a fancy term for combining or appending two strings. For example, concatenating the strings "Jeff" and "Kent" results in the string "Jeff Kent". Indeed, concatenation is a form of addition involving strings.

The following example uses the & operator to concatenate a string literal ("Hello ") and a string variable (myStr) to output "Hello World":

Dim myStr As String myStr = "World"

Debug.Write('Hello " & myStr)

The concatenation operator is required to append the string stored in the string variable myStr to the string literal. String literals are enclosed in double quotes, but string variables are not. If you enclose the string vari able in double quotes, Visual Basic .NET will interpret the reference to myStr as a string literal, and the output will be the name of the variable, not its value. For example, the following example will output "Hello myStr".

Dim myStr As String myStr = "World"

Debug.Write("Hello myStr")

The concatenation operator permits you to separate the part of the "Hello World" string that is a string variable from the part that is the string literal.

Similarly, you can use the concatenation operator to separate a literal from an expression. The following statement will output "2 squared is 4":

Debug.Write("2 squared is " & 2A2)

Similarly, the following statement will output "2 squared is 4 and 2 cubed is 8":

Debug.Write('2 squared is " & 2A2 & " and 2 cubed is " & 2A3)

You also can use the + operator to concatenate strings. The + operator is overloaded, performing both addition of numbers and concatenation of strings. I recommend that you use only the & operator, and not the + operator, to concatenate strings. Using th e + operator for string concatenation as well as numerical addition creates an ambiguity whether addition or string concatenation is intended or will occur.

Was this article helpful?

0 0

Post a comment