I'm a beginner in C#, just have some question on string concatenation.
string str = "My name is";
str += "John"
Q1-Does C#(.NET) have the same concept string pool in Java?
Q2- how many string object are created?
I'm a beginner in C#, just have some question on string concatenation.
string str = "My name is";
str += "John"
Q1-Does C#(.NET) have the same concept string pool in Java?
Q2- how many string object are created?
Q1-Does C#(.NET) have the same concept string pool in Java?
T̶h̶e̶ ̶a̶n̶s̶w̶e̶r̶ ̶i̶s̶ ̶n̶o̶,̶ ̶u̶s̶i̶n̶g̶ ̶s̶t̶r̶i̶n̶g̶s̶ ̶i̶n̶ ̶C̶#̶ ̶i̶s̶ ̶n̶o̶t̶ ̶l̶i̶k̶e̶ ̶t̶h̶e̶ ̶s̶t̶r̶i̶n̶g̶ ̶p̶o̶o̶l̶ ̶i̶n̶ ̶j̶a̶v̶a̶, each string is its own reference;
Correction : I had to research this for Java... It is conceptually the same thing, i was mistaken about the details of Javas string pool
C# commonly calls it string interning
You can read more about it here at Fabulous Adventures In Coding : Eric Lippert's Erstwhile Blog
String interning and String.Empty
If you have two identical string literals in one compilation unit then the code we generate ensures that only one string object is created by the CLR for all instances of that literal within the assembly. This optimization is called "string interning".
String interning is a CLI feature that reuses a string instance in certain situations :
string
literals, created via the ldstr
IL commandstring.Intern
Q2- how many string object are created?
Because strings in C# are immutable, you get 3 string allocations out of your 2 statements
// 1st string
string str = "My name is";
// 2nd string
// "John"
// 3rd string, which is the concatenation of the first 2
str += "John"
Yes, there is such a thing.
The common language runtime conserves string storage by maintaining a table, called the intern pool, that contains a single reference to each unique literal string declared or created programmatically in your program. Consequently, an instance of a literal string with a particular value only exists once in the system. source
In your case, I believe there will be three allocations.