The difference between + and & for joining strings in VB.NET

What is the difference between + and & for joining strings in VB.NET?


Solution 1:

There's no difference if both operands are strings. However, if one operand is a string, and one is a number, then you run into problems, see the code below.

"abc" + "def" = "abcdef"
"abc" & "def" = "abcdef"
"111" + "222" = "111222"
"111" & "222" = "111222"
"111" & 222 = "111222"
"111" + 222 = 333
"abc" + 222 = conversion error

Therefore I recommend to always use & when you mean to concatenate, because you might be trying to concatenate an integer, float, decimal to a string, which will cause an exception, or at best, not do what you probably want it to do.

Solution 2:

The & operator always makes sure that both operands are strings, while the + operator finds the overload that matches the operands.

The expression 1 & 2 gives the value "12", while the expression 1 + 2 gives the value 3.

If both operands are strings, there is no difference in the result.

Solution 3:

None.

As you can see below. These two lines of code compiles exactly to the same CIL code:

Module Module1

    Sub Main()
        Dim s1 As String = "s1"
        Dim s2 As String = "s2"
        s2 += s1
        s1 &= s2
    End Sub

End Module

Compiles to (note System.String::Concat):

.method public static void  Main() cil managed
{
.entrypoint
.custom instance void [mscorlib]System.STAThreadAttribute::.ctor() = ( 01 00 00 00 )
// Code size       31 (0x1f)
.maxstack  2
.locals init ([0] string s1,
       [1] string s2)
IL_0000:  nop
IL_0001:  ldstr      "s1"
IL_0006:  stloc.0
IL_0007:  ldstr      "s2"
IL_000c:  stloc.1
IL_000d:  ldloc.1
IL_000e:  ldloc.0
IL_000f:  call       string [mscorlib]System.String::Concat(string,
                                                          string)
IL_0014:  stloc.1
IL_0015:  ldloc.0
IL_0016:  ldloc.1
IL_0017:  call       string [mscorlib]System.String::Concat(string,
                                                          string)
IL_001c:  stloc.0
IL_001d:  nop
IL_001e:  ret
} // end of method Module1::Main