String manipulation with & or + in VB.NET

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.

Leave a Comment