Concat strings by & and + in VB.Net
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()
& 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
- You should definitely turn
Option Strict On
, then the compiler will force you to add explicit casts where it thinks they are necessary. - You should avoid using
+
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)