Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Concatenation using '+' operator

Tags:

string

c#

.net

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)

like image 919
NoviceProgrammer Avatar asked Apr 26 '12 20:04

NoviceProgrammer


People also ask

What is the operator for string concatenation?

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

Can we add two string using operator?

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.

Which operator is used for string concatenation in C?

The '+' operator adds the two input strings and returns a new string that contains the concatenated string.

How do you concatenate strings?

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.


1 Answers

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.

like image 57
Jon Skeet Avatar answered Oct 17 '22 04:10

Jon Skeet