0

Please see the code below:

Dim str1 As String="Test"
Dim int1 As Integer = 1
Dim str2 = str1 & int1

Should int1 be casted into a string before it is concatenated or does it make no difference?

I have recently turned OPTION STRICT ON in a VB.NET app

w0051977
  • 15,099
  • 32
  • 152
  • 329

3 Answers3

2

See String manipulation with & or + in VB.NET.

Using the & operator indicates your intention to concatenate strings, while the + operator indicates your intention to add numbers. Using the & operator will convert both sides of the operation into strings.

& always returns String.

Community
  • 1
  • 1
spongebob
  • 8,370
  • 15
  • 50
  • 83
1

This is a very poor question but I'll answer it anyway. The result is: no, casting is not needed. In your case str2 will be Test1.

Internally the code will use String.Concat() method, which takes objects and calls ToString() on the object. And since everything in .NET derives from object, this will work.

Abbas
  • 14,186
  • 6
  • 41
  • 72
0

The concatenation (&) operator can convert a number to a string implicitly.

In addition, If I had any doubts I would use TypeName to determine the type of the variable In your case:

 TypeName(str2)

Also, If Option Strict is on, the implicit narrowing conversion causes a compile-time error, In this case it is Widening conversion.

Ravi Yenugu
  • 3,895
  • 5
  • 40
  • 58