Why not use '+' for concatenation?

hellsgate

Member
Joined
Apr 21, 2007
Messages
14
Programming Experience
1-3
Hey guys,

A little while back I had a data access problem which cjard helped me out with, but he also mentioned at the time that
Aside from the fact that we dont use + to concatenate strings in VB.NET

Can anyone explain to me why the + sign shouldn't be used? Thanks
 
The & operator is recommended for string concatenation because it is defined exclusively for strings and reduces your chances of generating an unintended conversion.
'+' is also the mathematical addition operator, so in the case one of the operands is a numeric data type and the other a string it will try to cast the string to number and add them, or throw exception if the string don't cast to number. some examples:
VB.NET:
Dim s As String = "1" + "1" 'results "11"
Dim s As String = "1" + 1 'results "2"
Dim s As String = "p1" + 1 'results InvalidCastException
 
Back
Top