Ampersand vs. Plus for string concatenation in VB.NET

In VB.NET, is there any advantage to using & to concatenate strings instead of + ?

for example

 Dim x as String = "hello" + " there" 

against.

 Dim x as String = "hello" & " there" 

Yes, I know that for a lot of string concatenations, I would like to use StringBuilder , but this is a more general question.

+52
string-concatenation
Jun 09 '10 at 13:21
source share
5 answers

I have heard good, strong arguments in favor of both operators. Which argument the day wins depends a lot on your situation. The only thing I can say is that you have to standardize one or the other. The code that mixes the two asks for confusion later.

Two arguments that I remember now for supporting & :

  • If you do not use Option Strict and have two number lines, it will be easy for the compiler to confuse the value of the + operator with, as you know, arithmetic addition
  • If you upgrade a lot of the old code from the vb6 era, it helps not to convert the concatenation operators (and remember: we need consistency).

And for + :

  • If you have a mixed vb / C # store, it would be nice to have only one concatenation operator. This makes it easier to move code between languages ​​and greatly reduces context switching for programmers when moving back and forth between languages.
  • & almost unique to VB, while + between lines in many languages ​​is understood as concatenation, so you will improve readability a bit.
+39
Jun 09 '10 at 13:29
source share

Micorosoft preference for VB programmers for use and for strings, NOT +.

You can also use the + operator to concatenate strings. However, to eliminate the ambiguity, you must use the and operator instead.

+40
Jun 09 '10 at 14:15
source share

I prefer to use & for string concatenations in VB.NET

One reason for this is to avoid confusion, for example,

 MessageBox.Show(1 & 2) ' "12" MessageBox.Show(1 + 2) ' 3 
+12
Jun 09 '10 at 13:28
source share

This is safer to use, and since you make your intent clear to the compiler (I want to combine these two values, and they both need to be converted to strings).

Using + can make it difficult to find errors if the strings are numeric values, at least if the strict parameter is disabled.

For example:

 1 + "1" = 2 ' this fails if option strict is on 1 & "1" = 11 

Edit: although if you are concatenating a non-string, you should probably use some better method.

+10
Jun 09 '10 at 13:25
source share

I believe this is historical (not .NET Visual Basic uses &, not sure why they introduced +) and a question of taste (I prefer, and because we concatenate strings, we don't add them ...).

+5
Jun 09 '10 at 13:24
source share



All Articles