24

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
Bobby
  • 11,419
  • 5
  • 44
  • 69
Javed Akram
  • 15,024
  • 26
  • 81
  • 118
  • I had no idea `+` was even a concatenation operator in VB. That's one of the things I hate about JavaScript is that `+` is for concat and addition. – Brad Jan 12 '11 at 15:49
  • 5
    @Brad: Does that mean you also hate C#? Or is this hatred reserved only for "uncool" languages like VB.NET and JavaScript? The separate `&` concatenation operator is one of the things I *love* about VB. And if you're using `+` when there's an alternative available, that's not the language's fault, it's your fault as a programmer for not knowing the language. – Cody Gray - on strike Jan 16 '11 at 07:43
  • 1
    @Cody, you misunderstand, I don't really hate any languages as a whole. I simply hate the fact that `+` doubles as a concatenation operator in some languages, and I used JavaScript as an example, as that's where I deal with it the most. I completely agree, I love the fact that `&` is a separate concat operator in VB, and that's all I knew even existed as a concat operator in VB until now. VB is my primary language for desktop applications. – Brad Jan 16 '11 at 17:41
  • @Brad: Fair enough. Thanks for the explanation, and I'm sorry if I sounded like I was jumping to criticize you. I just see a lot of misdirected language elitism recently, and that bothers me. – Cody Gray - on strike Jan 17 '11 at 04:27
  • @Cody, no worries, it bothers me too. – Brad Jan 17 '11 at 14:13

8 Answers8

34

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

N. Hodin
  • 1,056
  • 6
  • 12
26
  • & 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)

MarkJ
  • 30,070
  • 5
  • 68
  • 111
5

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()

Chris B. Behrens
  • 6,255
  • 8
  • 45
  • 71
  • 1
    It's the same problem, the other way round...it's trying to cast the s1 to an int and failing. To fix that, use the first line and not the second. – Chris B. Behrens Jan 12 '11 at 15:14
  • 1
    Sadly I think this is wrong. Option Strict must be Off otherwise this wouldn't compile, never mind runtime exceptions. My advice would be to turn Option Strict On and then fix the compiler errors with explicit casts. – MarkJ Jan 12 '11 at 16:40
  • 1
    ...Just checked, if Option Strict is on, the compiler gives an error on `s = s1 & i`. *Error 1 Option Strict On disallows implicit conversions from 'String' to 'Double'.* – MarkJ Jan 12 '11 at 16:56
2

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.

Mark Hurd
  • 10,665
  • 10
  • 68
  • 101
0

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

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

output will be:

5577:wscript.exe
Shubham Verma
  • 8,783
  • 6
  • 58
  • 79
0

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
Ewan
  • 1
-1

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?

Community
  • 1
  • 1
Buck Hicks
  • 1,534
  • 16
  • 27
  • 2
    Single line string concatenation is generally *faster* than calling `String.Format`. Any advice to always use one over the other is wrong, and this is no exception. Take advantage of compiler optimizations. This idea of doing something to "make your code look more professional" is stupid. That's the kind of thing that justifies using C++ when your task is made much easier with a dynamic scripting language because oh, that just look too "unprofessional". Professional software is stuff that *works*...well. Appearance is irrelevant. The answers in the question you linked appear to confirm this. – Cody Gray - on strike Jan 16 '11 at 07:39
-2

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.

Alex7575
  • 65
  • 2
  • A `StringBuilder` is *not* going to help in this case. When you're dealing with less than (approximately) 4 appends, the overhead of `StringBuilder` is generally not worth it. The asker isn't appending strings in a loop, so there's no point. Before making recommendations, understand what the things you're recommending actually *do* and how they work. Ditch the cargo-cult programming routine. – Cody Gray - on strike Jan 16 '11 at 07:41
  • 1
    "If you are concatenating a significant amount of strings" – Alex7575 Jan 18 '11 at 16:42
  • 1
    @Cody take it easy, buddy. Nobody's getting hurt here. –  Jan 18 '11 at 17:39
  • 3
    @Will: Wow, I didn't realize there was anything offensive or hostile about my comment. My apologies; nothing of the sort was meant. I'd just like to see answers taking the time to explain their reasoning rather than simply declaring "you should always do x". And for what it's worth, I meant that the question doesn't point towards a massive amount of concats, not the answer. – Cody Gray - on strike Jan 18 '11 at 22:46
  • @Cody Agree on your assessment completely. Sometimes people can interpret tone differently in comments. Unless you plaster them with smiley faces everywhere :). –  Jan 19 '11 at 14:03
  • And this is exactly the pariah of our profession, condescending attitutes. Good day for the both of you. – Alex7575 Jan 19 '11 at 16:50