Concat strings by & and + in VB.Net

后端 未结 8 814
萌比男神i
萌比男神i 2020-12-16 10:53

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?

相关标签:
8条回答
  • 2020-12-16 11:22

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

    0 讨论(0)
  • 2020-12-16 11:24

    You've probably got Option Strict turned on (which is a good thing), and the compiler is telling you that you can't add a string and an int. Try this:

    t = s1 & i.ToString()

    0 讨论(0)
  • 2020-12-16 11:24

    My 2 cents:

    If you are concatenating a significant amount of strings, you should be using the StringBuilder instead. IMO it's cleaner, and significantly faster.

    0 讨论(0)
  • 2020-12-16 11:25

    Try this. It almost seemed to simple to be right. Simply convert the Integer to a string. Then you can use the method below or concatenate.

    Dim I, J, K, L As Integer
    Dim K1, L1 As String
    
    K1 = K
    L1 = L
    Cells(2, 1) = K1 & " - uploaded"
    Cells(3, 1) = L1 & " - expanded"
    
    MsgBox "records uploaded " & K & " records expanded " & L
    
    0 讨论(0)
  • 2020-12-16 11:28

    As your question confirms, they are different: & is ONLY string concatenation, + is overloaded with both normal addition and concatenation.

    In your example:

    • because one of the operands to + is an integer VB attempts to convert the string to a integer, and as your string is not numeric it throws; and

    • & only works with strings so the integer is converted to a string.

    0 讨论(0)
  • 2020-12-16 11:28

    From a former string concatenater (sp?) you should really consider using String.Format instead of concatenation.

        Dim s1 As String
        Dim i As Integer
        s1 = "Hello"
        i = 1
        String.Format("{0} {1}", s1, i)
    

    It makes things a lot easier to read and maintain and I believe makes your code look more professional. See: code better – use string.format. Although not everyone agrees When is it better to use String.Format vs string concatenation?

    0 讨论(0)
提交回复
热议问题