Combining strings in VB.NET is a simple operation. You can utilize the & operator to add a string to the end of another string, or use the Insert method of a String object to insert a string within another string. While both & and + operators allow you to combine the strings, it's usually a good idea to use the & operator because the + operator will convert values into a Double if one of the values is a non-string expression.
Using the & operator, VB.NET attempts to convert any non-string values to a string and then concatenate them. The & operator for adding strings is said to be unambiguous since it's limited to performing the string concatenation even when the data types are not string. Here's an example:
Private Function ConcatenateStrings() As Integer
Dim strNameFirst As String = "James"
Dim strNameLast As String = "Lipton"
Dim strNameFull As String
strNameFull = strNameFirst & strNameLast
strNameFull = strNameFull.Insert(Len(strNameFirst), " ")
Initially, two variables are defined to hold two strings that are to be combined (strNameFirst and strNameLast). We use the & operator to combine the values of these strings into a third string (strNameFull). At this point strNameFull equals "JamesLipton". In order to add a space between the first and the last names, we utilize the Insert method of the String class that allows adding a character in the middle of the string. We specify where the character should be added and what character to add. In our example, we simply add a space between the first name and the last name.
Miss a tip?
Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!