Concat strings by & and + in VB.Net

后端 未结 8 815
萌比男神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:40
    • & 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)

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

    You can write '&' to add string and integer :

    processDetails=objProcess.ProcessId & ":" & objProcess.name
    message = msgbox(processDetails,16,"Details")
    

    output will be:

    5577:wscript.exe
    
    0 讨论(0)
提交回复
热议问题