+ verus &

Posted Sat, Aug 20 2005 17:56 by bill

 

The other day I saw someone not too familiar with VB get confused over whether they should use + instead of & or not. So, I'll try to explain....

 

& is the String concatenation operator.  If it is String concatenation you are trying to do, it is the operator you should use.  If either operand is not of type String, Char or Char(), the operand once converted to String is used.  The conversion for intrinsic types has special handling, but basically it calls the ToString for intrinsic types as well as for custom types.  Hence 1 & 2 will return a string "12".

 

+ is the addition operator.  When both operands are String, Char, or Char() or any combination there-of, then the + operator does String concatenation.  But it is not limited to that, it also does mathematical operations, etc. . Mathematical operations are given precedence over String concatenation, so 1 + "2" will return 3, as will "1" + 2, but "1" + "2" will return "12".   Obviously  code such as 1 + "2" requires Option Strict Off , where implicit conversions are allowed. If Strict On semantics are used, no conversions other than the implicit conversion of Char and Char() to String are applied

 

So the key points to remember are :

  • & will implicitly call ToString on the operands if necessary.  It behaves exactly the same whether you compile with Strict On or Strict Off.
  • + will behave differently depending on whether Strict On or Strict Off is used. It will only perform String concatenation if both operands are String, Char, Char() or a combination there-of, in other cases it will attempt to do addition .

 

You can of course use + with Strict semantics and when dealing only with String, Char and/or Char() it will work the same as &, but for other types, it requires you to do the conversion to string. So a blind equivalent of & is CStr(operand1) + CStr(operand2).

 

So the long and short of it, is use & when you explicitly want to do String concatenation.  No doubt some of you are saying well why have + for strings then ?  The answer of course lies in dynamic programming needs, where you do want/need two explicit operators, e.g: 1 + "2" versus 1 & "2". 

Filed under: