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)
In many programming languages, string concatenation is a binary infix operator. The + (plus) operator is often overloaded to denote concatenation for string arguments: "Hello, " + "World" has the value "Hello, World" .
The task is to concatenate the two strings using Operator Overloading in C++. Recommended: Please try your approach on {IDE} first, before moving on to the solution. Approach 1: Using unary operator overloading. To concatenate two strings using unary operator overloading.
The '+' operator adds the two input strings and returns a new string that contains the concatenated string.
Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With