Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concat strings by & and + in VB.Net

Tags:

Is there any difference between & and + operators while concatenating string? if yes, then what is difference? And if No, then why below code generating exception?

Example:

    Dim s, s1, t As String     Dim i As Integer      s1 = "Hello"     i = 1      s = s1 & i     t = s1 + i  //Exception here      If s = t Then         MessageBox.Show("Equal...")     End If 
like image 469
Javed Akram Avatar asked Jan 12 '11 15:01

Javed Akram


People also ask

Can you use += for string concatenation?

Concatenation is the process of combining two or more strings to form a new string by subsequently appending the next string to the end of the previous strings. In Java, two strings can be concatenated by using the + or += operator, or through the concat() method, defined in the java. lang. String class.

Does concat work on strings?

The concat() function concatenates the string arguments to the calling string and returns a new string.

Can you concat strings in Python?

In Python, you can concatenate two different strings together and also the same string to itself multiple times using + and the * operator respectively.


2 Answers

& and + are both concatenation operators but when you specify an integer while using +, vb.net tries to cast "Hello" into integer to do an addition. If you change "Hello" with "123", you will get the result 124.

like image 156
N. Hodin Avatar answered Oct 31 '22 00:10

N. Hodin


  • & is only used for string concatenation.
  • + is overloaded to do both string concatenation and arithmetic addition.

The double purpose of + leads to confusion, exactly like that in your question. Especially when Option Strict is Off, because the compiler will add implicit casts on your strings and integers to try to make sense of your code.

My recommendations

  • You should definitely turn Option Strict On, then the compiler will force you to add explicit casts where it thinks they are necessary.
  • You should avoid using + for concatenation because of the ambiguity with arithmetic addition.

Both these recommendations are also in the Microsoft Press book Practical Guidelines And Best Practises for VB and C# (sections 1.16, 21.2)

like image 26
MarkJ Avatar answered Oct 31 '22 01:10

MarkJ