Can someone explain the difference?
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
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.
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 is especially can be bad in 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 :)
There's no differnce if both operands are strings. However if one operand is a string, and one is a number, then you run into problems, see 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.
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.
If both of the types are statically typed to System.String, there is 0 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, VB late binding will kick and 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 concat. The VB runtime will go through all manner of conversions to convert both values to strings. It will then String.Concat the results.