Overly Excessive
Overly Excessive

Reputation: 2125

Modification of strings

I understand that strings are an immutable reference type in C#. But I have a more specific question.

string a = "hello ";
string b = a;
a += "world";
Console.WriteLine(b);

The code above will produce the output hello. I realize that this is because strings are immutable so once we have created an instance of a string with the value "hello " it cannot be modified. But I want to know, what happens when we do a += "world" ? Looking at the IL doesn't seem to give me the whole story unfortunately (or it might be that I am too novice to see the bigger picture)

IL_0001:  ldstr       "hello "
IL_0006:  stloc.0     // a
IL_0007:  ldloc.0     // a
IL_0008:  stloc.1     // b
IL_0009:  ldloc.0     // a
IL_000A:  ldstr       "world"
IL_000F:  call        System.String.Concat
IL_0014:  stloc.0     // a
IL_0015:  ldloc.0     // a
IL_0016:  call        System.Console.WriteLine

The IL reveals to me what I had already guessed that the string "hello " is concatenated into with "world" to form a new string. But does this mean that what this line actually does is to:

  1. Create a new instance of a string object with the value "world".
  2. Read the value of our first string object "hello" and then concatenate that value with "world" to form a third string.
  3. Return the reference of aforementioned string to a.
  4. The "world" string instance is now orphaned and marked for collection?

Or am I completely wrong here? I really want to know what's going on "behind the scenes" or so to say..

Upvotes: 4

Views: 127

Answers (4)

drew_w
drew_w

Reputation: 10430

Because strings are immutable one equivalent to your program is:

string a = "hello ";
string b = a;
a = new string(a + "world");

Because strings are immutable the new operator is basically included for you.

In case you were interested, internally strings are stored as character arrays (see here). They are actually stored on the heap which is why careful use of strings is important (heap memory isn't unlimited). I also found this other relevant stack question here: How are String and Char types stored in memory in .NET?

Upvotes: 1

DLeh
DLeh

Reputation: 24395

When you do a+="World", it creates a new string with the value a + "world". Since hello is still being used by b, it is not yet garbage collected.

Upvotes: 0

Christos
Christos

Reputation: 53958

When you write a += "world" is as you were writing a = a + "world", which actually creates a new string from the concatenation of the strings a and "world" and then assigns the result to the a.

Upvotes: 1

Deduplicator
Deduplicator

Reputation: 45654

Yes, a += "world"; really does what you puzzled out, being equivalent to a = a + "world";.

That's a case of += being strictly only syntactic sugar. Still, who doesn't like some sweets?

Upvotes: 1

Related Questions