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:
There is also a super article from Joel referred in part 2 (http://www.joelonsoftware.com/articles/fog0000000319.html)
It doesn’t – the C# compiler does 🙂
So this code:
actually gets compiled as:
(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 + ywhich then needs to be copied again as part of the concatenation of(x + y)andz. 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:
just ends up as equivalent to:
… so this does generate a lot of garbage, and it’s why you should use a
StringBuilderfor such cases. I have an article going into more details about the two which will hopefully answer further questions.