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?
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.
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.
There are two types of methods in String : shared methods and instance methods.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With