Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The difference between + and & for joining strings in VB.NET

Tags:

string

vb.net

What is the difference between + and & for joining strings in VB.NET?

like image 830
Rob P. Avatar asked Apr 09 '09 14:04

Rob P.


2 Answers

There's no difference if both operands are strings. However, if one operand is a string, and one is a number, then you run into problems, see the code below.

"abc" + "def" = "abcdef" "abc" & "def" = "abcdef" "111" + "222" = "111222" "111" & "222" = "111222" "111" & 222 = "111222" "111" + 222 = 333 "abc" + 222 = conversion error 

Therefore I recommend to always use & when you mean to concatenate, because you might be trying to concatenate an integer, float, decimal to a string, which will cause an exception, or at best, not do what you probably want it to do.

like image 134
Kibbee Avatar answered Nov 24 '22 23:11

Kibbee


The & operator always makes sure that both operands are strings, while the + operator finds the overload that matches the operands.

The expression 1 & 2 gives the value "12", while the expression 1 + 2 gives the value 3.

If both operands are strings, there is no difference in the result.

like image 25
Guffa Avatar answered Nov 24 '22 22:11

Guffa