Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic casting to string in C# and VB.NET

Tags:

c#

casting

vb.net

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?

like image 997
Sprintstar Avatar asked Nov 29 '22 21:11

Sprintstar


1 Answers

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.)

like image 83
Jon Skeet Avatar answered Dec 05 '22 01:12

Jon Skeet