Memory assigned to strings

I know that strings in C# are immutable i.e. when I change the value of a string variable a new string variable with the same name is created with the new value and the older one is collected by GC. Am I right?

string s1 = "abc";
s1 = s1.Substring(0, 1);

If what I said is right, then my doubt is if a new string is created, then is it created in the same memory location?

Jon Skeet
people
quotationmark

if a new string is created, then is it created in the same memory location?

No, a separate string object is created, in a separate bit of memory.

You're then replacing the value of s1 with a reference to the newly-created string. That may or may not mean that the original string can be garbage collected - it depends on whether anything else has references to it. In the case of a string constant (as in your example, with a string literal) I suspect that won't be garbage collected anyway, although it's an implementation detail.

If you have:

string text = "original";
text = text.Substring(0, 5);
text = text.Substring(0, 3);

then the intermediate string created by the first call to Substring will be eligible for garbage collection, because nothing else refers to it. That doesn't mean it will be garbage collected immediately though, and it certainly doesn't mean that its memory will be reused for the string created by the final line.

people

See more on this question at Stackoverflow