26

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
5
  • 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. Commented Jan 12, 2011 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. Commented Jan 16, 2011 at 7: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. Commented Jan 16, 2011 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. Commented Jan 17, 2011 at 4:27
  • @Cody, no worries, it bothers me too. Commented Jan 17, 2011 at 14:13

8 Answers 8

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.

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

Comments

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)

Comments

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

3 Comments

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.
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.
...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'.
3

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.

Comments

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

Comments

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

Comments

-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?

1 Comment

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

6 Comments

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.
"If you are concatenating a significant amount of strings"
@Cody take it easy, buddy. Nobody's getting hurt here.
@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 Agree on your assessment completely. Sometimes people can interpret tone differently in comments. Unless you plaster them with smiley faces everywhere :).
|

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.