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?
Example:
Dim s, s1, t As String Dim i As Integer s1 = "Hello" i = 1 s = s1 & i t = s1 + i //Exception here If s = t Then MessageBox.Show("Equal...") End If
Concatenation is the process of combining two or more strings to form a new string by subsequently appending the next string to the end of the previous strings. In Java, two strings can be concatenated by using the + or += operator, or through the concat() method, defined in the java. lang. String class.
The concat() function concatenates the string arguments to the calling string and returns a new string.
In Python, you can concatenate two different strings together and also the same string to itself multiple times using + and the * operator respectively.
& 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.
& is only used for string concatenation. + is overloaded to do both string concatenation and arithmetic addition.The double purpose of + leads to confusion, exactly like that in your question. Especially when Option Strict is Off, because the compiler will add implicit casts on your strings and integers to try to make sense of your code.
My recommendations
Option Strict On, then the compiler will force you to add explicit casts where it thinks they are necessary. + for concatenation because of the ambiguity with arithmetic addition. Both these recommendations are also in the Microsoft Press book Practical Guidelines And Best Practises for VB and C# (sections 1.16, 21.2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With