tags:

views:

2207

answers:

4

I could do this in C#..

int number = 2;
string str = "Hello " + number + " world";

..and str ends up as "Hello 2 world".

In VB.NET i could do this..

Dim number As Integer = 2
Dim str As String = "Hello " + number + " world"

..but I get an InvalidCastException "Conversion from string "Hello " to type 'Double' is not valid."

I am aware that I should use .ToString() in both cases, but whats going on here with the code as it is?

+10  A: 

In VB I believe the string concatenation operator is & rather than + so try this:

Dim number As Integer = 2
Dim str As String = "Hello " & number & " world"

Basically when VB sees + I suspect it tries do numeric addition or use the addition operator defined in a type (or no doubt other more complicated things, based on options...) Note that System.String doesn't define an addition operator - it's all hidden in the compiler by calls to String.Concat. (This allows much more efficient concatenation of multiple strings.)

Jon Skeet
+5  A: 

Visual Basic makes a destinction between the + and & operators. The & will make the conversion to a string if an expression it not a string.

&Operator (Visual Basic)

http://msdn.microsoft.com/en-us/library/wfx50zyk.aspx

The + operator uses more complex evaluation logic to determin what to make the final cast into (for example it's affected by things like Option Strict configuration)

+Operator (Visual Basic)

http://msdn.microsoft.com/en-us/library/9c5t70w2.aspx

TheCodeJunkie
+1  A: 

The VB plus (+) operator is ambiguous.

If you don't have Option Explicit on, if my memory serves me right, it is possible to do this:

Dim str = 1 + "2"

and gets str as integer = 3.

If you explicitly want a string concatenation, use the ampersand operator

Dim str = "Hello " & number & " world"

And it'll happily convert number to string for you.

I think this behavior is left in for backward compatibility.

When you program in VB, always use an ampersand to concatenate strings.

chakrit
+1  A: 

I'd suggest to stay away from raw string concatenation, if possible.

Good alternatives are using string.format:

str = String.Format("Hello {0} workd", Number)

Or using the System.Text.StringBuilder class, which is also more efficient on larger string concatenations.

Both automatically cast their parameters to string.

Loris