69

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

Dan Atkinson
  • 10,801
  • 12
  • 78
  • 106
Rob P.
  • 14,168
  • 14
  • 67
  • 104

8 Answers8

91

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Kibbee
  • 62,900
  • 26
  • 139
  • 178
  • 11
    Or always enforce Option Strict On, in which case you never need to worry about it. Option Strict On has numerous other advantages as well: http://stackoverflow.com/questions/222370/option-strict-on-and-net-for-vb6-programmers – mattmc3 Jul 19 '10 at 03:55
  • 3
    There is a problem with `&` for string concatenation. From the [documentation](http://msdn.microsoft.com/en-us/library/te2585xw.aspx) "The & operator always widens its operands to String, regardless of the setting of Option Strict". So for example `"Hello " & 2.5` will silently convert the 2.5 to a string using the regional settings (you might get `"2.5"` or `"2,5"`). Fine if that was what you wanted. I would much, much rather be forced to specify explicitly. – MarkJ Sep 19 '11 at 10:24
  • @MarkJ Oh yeah, that regional stuff can really get you if you don't watch it. Especially on web servers. If you have a bunch of web servers, you should make sure they are all configured to the same regional settings, lets you get wierd formatting problems with numbers and dates. – Kibbee Sep 19 '11 at 12:33
  • 5
    For completeness, it should also be worth noting what is returned when you perform `"abc" & 222` (`"abc222"`). – Dan Atkinson Jan 09 '14 at 11:29
  • 2
    Let me mention that `333` in the next-to-last line is actually of type `System.Double`. – Vladimir Reshetnikov Aug 15 '17 at 21:11
13

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.

Guffa
  • 640,220
  • 96
  • 678
  • 956
  • + operator only carries out implicit conversion if `Option Strict` is `Off`. But & operator will carry out implicit conversion to string regardless of the `Option Strict` setting. [Documentation](http://msdn.microsoft.com/en-us/library/te2585xw.aspx) "The & operator always widens its operands to String, regardless of the setting of Option Strict". So for example `"Hello " & 2.5` will silently convert the 2.5 to a string using the regional settings (you might get `"2.5"` or `"2,5"`). Fine if that was what you wanted. – MarkJ Sep 19 '11 at 10:26
8

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
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Aliostad
  • 76,981
  • 19
  • 152
  • 203
  • Thanks Aliostad, that sums it up perfectly. I was most curious (and probably should have outlined it a bit better in my question) to how it was handled. String + String (as long as they're both strings) is the same as String & String (regardless of a complex set of rules with the + operator). – rickp Sep 13 '10 at 19:45
  • No probs. It is always good to have a look at the IL code using ILDASM. Initially it is unfamiliar but gradually you get used to it. – Aliostad Sep 13 '10 at 19:48
3

The + operator can be either addition or concatenation. The & is only concatenation. If the expressions are both strings the results would be the same.

I use & when working with strings, and + when working with numbers, so there is never confusion about my intent. If you mistakenly use + and one expression is a string and one is a number, you run the risk of un-desired results.

dbasnett
  • 10,010
  • 2
  • 22
  • 32
2

There is no difference in most of the cases. However, the best practice is:

"+" should be reserved for integer additions, because if you don't use Option Strict On then you might have really messed up situations such as:

Input + 12 might give you 20 instead of 812. This can be especially bad in an ASP.NET application where the input comes from POST/GET.

Simply put: For joining strings, always use "&" instead of "+".

Obviously, use StringBuilder where it's suitable :)

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
dr. evil
  • 25,988
  • 28
  • 126
  • 198
1

Straight from MSDN Documentation: Concatenation Operators in Visual Basic

Differences Between the Two Concatenation Operators

The + Operator (Visual Basic) 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 (Visual Basic) 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.

Do trust MSDN! :-)

FranciscoBouza
  • 517
  • 6
  • 18
1

If both of the types are statically typed to System.String, there is zero difference between the code. Both will resolve down to the String.Concat member (this is what + does for strings).

However, if the objects are not strongly typed to string, Visual Basic late binding will kick in and go two very different routes. The + version will attempt to do an add operation which literally tries to add the objects. This will do all manner of attempts to convert both values to a number and then add them.

The & operator will attempt to concatenate. The Visual Basic runtime will go through all manner of conversions to convert both values to strings. It will then String.Concat the results.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
JaredPar
  • 673,544
  • 139
  • 1,186
  • 1,421
  • Also worth mentioning that the `&` operator **disregards Option Strict**. From the [documentation](http://msdn.microsoft.com/en-us/library/te2585xw.aspx) "The & operator always widens its operands to String, regardless of the setting of Option Strict". So for example `"Hello " & 2.5` will silently convert the 2.5 to a string using the regional settings (you might get `"2.5"` or `"2,5"`). Fine if that was what you wanted. Contrast with `+` which is strict when `Option Strict On` – MarkJ Sep 19 '11 at 10:27
0

None when joining strings:

    Dim string1 As String = "A" + "B"
    Dim string2 As String = "A" & "B"

    If string1.Equals(string2) And string2.Equals(string1) Then
        Debugger.Break()
    End If
Gavin Miller
  • 40,636
  • 19
  • 113
  • 178