String manipulation with & or + in VB.NET
.net, string, vb.net
Solution
The `+` and `&` operators are not identical in VB.NET.
Using the `&` operator indicates your intention to concatenate strings, while the `+` operator indicates your intention to add numbers. Using the `&` operator will convert both sides of the operation into strings. When you have mixed types (one side of the expression is a string, the other is a number), your usage of the operator will determine the result.
1 + "2" = 3 'This will cause a compiler error if Option Strict is on'
1 & "2" = "12"
1 & 2 = "12"
"text" + 2 'Throws an InvalidCastException since "text" cannot be converted to a Double'
So, my guideline (aside from avoiding mixing types like that) is to use the `&` when concatenating strings, just to make sure your intentions are clear to the compiler, and avoid impossible-to-find bugs involving using the `+` operator to concatenate.
Problem
I have seen several programmers use `&` and `+` for string manipulation. Such as: ``` dim firstvar as string dim secondvar as string dim thirdvar as string thirdvar = firstvar & secondvar ``` Or is it: ``` thirdvar = firstvar + secondvar ``` Does it matter? If so, why?