The + operator

Posted Sun, Apr 23 2006 22:08 by bill
I was reading Billy Hollis's blog entry about strict typing and saw the examples of the use of the + operator with late bound code.  Go have a look, it is kind of fun to see how many you get right :)
 
Oh, and if you are wondering how to work them out the rules are actually very simple:
  • if both operands are numeric, the result is numeric using the wider type (eg: int + double returns a double
  • if one of the operands is numeric and the other string, a numeric operation is performed, the string being converted to double, hence the result is a double
  • for booleans the conversion is made to a 16 bit signed integer by default
  • a weird rule exists for when both operands are dates, the result being the addition if the date strings.
  • if both operands are string (or char), then a string concatenation is performed
 
Most of these rules will probably never both you except the second rule.  If one operand is a string and the other a numeric, then the string will be converted to a double (or crash and burn in trying to do so).

So if you have code like:
  Dim x As Int32 = 4
  Dim y as String = "2"
  Dim result As String = x + y
That code will (a) only compile with strict off semantics, and (b) return "6".

If you wanted 42, then use the concatenation operator, &.
 Dim result As String = x & y
will return 42 regardless of strict on or off semantics.

 
Filed under: ,

Comments

# The & operator (Concatenation)

Sunday, April 23, 2006 11:08 PM by @ Head

In my previous blog posting I talked briefly about the + operator, and hopefully people realized that...