What is the difference between + and & for joining strings in VB.NET?
What is the difference between + and & for joining strings in VB.NET?
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.
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 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 :)
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 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.
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