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

1
  • 4
    Why don't you try and find out? :) Commented Jun 25, 2014 at 14:27

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

1 Comment

or just hold your mouse over it to see the Type

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.