Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String manipulation with & or + in VB.NET

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?

like image 669
ErocM Avatar asked Jul 06 '09 16:07

ErocM


People also ask

What is a string manipulation?

String manipulation basically refers to the process of handling and analyzing strings. It involves various operations concerned with modification and parsing of strings to use and change its data.

What is string manipulation function with example?

String-manipulation functions accept arguments of type CHAR, NCHAR, VARCHAR, NVARCHAR, or LVARCHAR. You can use a string-manipulation function anywhere you use an expression. The following functions convert between upper and lowercase letters in a character string: LOWER.

How many types of string manipulation are there?

There are two types of methods in String : shared methods and instance methods.


3 Answers

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.

like image 105
bdukes Avatar answered Oct 08 '22 23:10

bdukes


Consider if you are better off using String.Format when concatenating strings. Usually, the code ends up making more sense that way.

Also, if you concatenate many times, consider using a StringBuilder rather than a String.

like image 25
Patrick Szalapski Avatar answered Oct 09 '22 01:10

Patrick Szalapski


In general, & will always concatenate strings regardless of types of arguments, while + will not. Since there's no drawback in using & over + otherwise, in situations where you clearly desire string concatenations, it is preferable. It also makes the intent of code slightly clearer.

like image 39
Pavel Minaev Avatar answered Oct 08 '22 23:10

Pavel Minaev