Is there any difference between & and + operators while concatenating string? if yes, then what is difference? And if No, then why below code generating exception?
& and + are both concatenation operators but when you specify an integer while using +, vb.net tries to cast "Hello" into integer to do an addition. If you change "Hello" with "123", you will get the result 124.
You've probably got Option Strict turned on (which is a good thing), and the compiler is telling you that you can't add a string and an int. Try this:
t = s1 & i.ToString()
My 2 cents:
If you are concatenating a significant amount of strings, you should be using the StringBuilder instead. IMO it's cleaner, and significantly faster.
Try this. It almost seemed to simple to be right. Simply convert the Integer to a string. Then you can use the method below or concatenate.
Dim I, J, K, L As Integer
Dim K1, L1 As String
K1 = K
L1 = L
Cells(2, 1) = K1 & " - uploaded"
Cells(3, 1) = L1 & " - expanded"
MsgBox "records uploaded " & K & " records expanded " & L
As your question confirms, they are different: &
is ONLY string concatenation, +
is overloaded with both normal addition and concatenation.
In your example:
because one of the operands to +
is an integer VB attempts to convert the string to a integer, and as your string is not numeric it throws; and
&
only works with strings so the integer is converted to a string.
From a former string concatenater (sp?) you should really consider using String.Format instead of concatenation.
Dim s1 As String
Dim i As Integer
s1 = "Hello"
i = 1
String.Format("{0} {1}", s1, i)
It makes things a lot easier to read and maintain and I believe makes your code look more professional. See: code better – use string.format. Although not everyone agrees When is it better to use String.Format vs string concatenation?