C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Step 1: Here we create 2 Strings (value1 and value2) with the literal values "Visual" and "Basic."
Step 2: We combine the strings with a plus and display the results with Console.WriteLine.
Step 3: We can use plus with more than 2 strings—here we place a 1-char string literal in between the 2 strings.
Step 4: We apply the String.Concat Function, which receives 2 or more Strings and combines them into a single String.
VB.NET program that concatenates strings
Module Module1
Sub Main()
' Step 1: declare 2 input strings.
Dim value1 As String = "Visual"
Dim value2 As String = "Basic"
' Step 2: concat with plus.
Dim value3 = value1 + value2
Console.WriteLine(value3)
' Step 3: concat with a space in between.
Dim value4 = value1 + " " + value2
Console.WriteLine(value4)
' Step 4: use String.Concat Function.
Dim value5 = String.Concat(value1, " ", value2)
Console.WriteLine(value5)
End Sub
End Module
Output
VisualBasic
Visual Basic
Visual Basic
Note: Usually it is best to keep a code base consistent, so if other code uses the ampersand, it is probably best to use it too.
VB.NET program that uses and to concatenate
Module Module1
Sub Main()
Dim left As String = "bird"
Dim right As String = " frog"
' Concatenate 2 strings with ampersand.
Dim result = left & right
Console.WriteLine("RESULT: " & result)
Console.WriteLine("LENGTH: " & result.Length)
End Sub
End Module
Output
RESULT: bird frog
LENGTH: 9
ParamArray: We can pass strings to String.Join and they are automatically added to a ParamArray. So we concat the strings with a separator.
ParamArrayVB.NET program that uses Join with ParamArray
Module Module1
Sub Main()
' Join the strings with a space in between.
Dim result As String = String.Join(" ", "bird", "cat", "frog")
Console.WriteLine("JOINED: {0}", result)
End Sub
End Module
Output
JOINED: bird cat frog
VB.NET program that causes error
Module Module1
Sub Main()
Dim value As String = "bird"
Dim number As Integer = 100
' This concatenation causes an error.
Dim result = value + number
End Sub
End Module
Output
Unhandled Exception: System.InvalidCastException:
Conversion from string "bird" to type 'Double' is not valid.
---> System.FormatException: Input string was not in a correct format.
at Microsoft.VisualBasic.CompilerServices.Conversions...
VB.NET program that concats Integer to String
Module Module1
Sub Main()
Dim value As String = "bird"
Dim number As Integer = 100
' Concat an integer.
Dim result = value + number.ToString()
' Write the string.
Console.WriteLine(result)
End Sub
End Module
Output
bird100