87

Looking at the string class metadata, I only see the operators == and != overloaded. So how is it able to perform concatenation for the '+' operator?

Edit:

Some interesting notes from Eric Lippert on string concatenation:

Part 1

Part 2

There is also a super article from Joel referred in part 2 (http://www.joelonsoftware.com/articles/fog0000000319.html)

1 Answer 1

145

It doesn't - the C# compiler does :)

So this code:

string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;

actually gets compiled as:

string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);

(Gah - intervening edit removed other bits accidentally.)

The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y which then needs to be copied again as part of the concatenation of (x + y) and z. Instead, we get it all done in one go.

EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:

string x = "";
foreach (string y in strings)
{
    x += y;
}

just ends up as equivalent to:

string x = "";
foreach (string y in strings)
{
    x = string.Concat(x, y);
}

... so this does generate a lot of garbage, and it's why you should use a StringBuilder for such cases. I have an article going into more details about the two which will hopefully answer further questions.

8
  • 8
    Good answer; just a follow-up question: if you're concatenating strings inside a loop, how does the compiler work the .Concat operator when it can't know in advance what's going to be in the loop.
    – frenchie
    Apr 26, 2012 at 20:49
  • Ah ok! And that's why it's better to use the StringBuilder for concatenations?
    – frenchie
    Apr 26, 2012 at 20:52
  • 4
    @frenchie: That's why it's better to use StringBuilder for repeated concatenation... but why it's not worth it for concatenation of a fixed number of values.
    – Jon Skeet
    Apr 26, 2012 at 20:53
  • @Jon-Skeet: thanks for the quick clarification...i should have checked in IL as well..and this is how int adds as well? by calling the Add method? Apr 26, 2012 at 20:57
  • 2
    But note that nowadays the string.Concat and string.Join methods have many overloads, including some taking in an IEnumerable<> instance. So they are more convenient to use in most cases than to use a StringBuilder (I don't know if these methods use a StringBuilder internally, I just say that they are more convenient in most cases). Jun 24, 2013 at 21:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.