String Modification

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);

In the above code, the output will be output hello. I understand that this is because the lines are immutable, therefore, as soon as we instantiate a line with the value "hello", it cannot be changed. But I want to know what happens when we do a += "world"? Looking at IL doesn't seem to give me the whole story, unfortunately (or maybe I'm too new to see the big 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

IL shows me that I already guessed that the string "hello" combines into a "world" to form a new line. But does this mean that this line really does this:

  • Create a new instance of the string object with the value "world".
  • "hello" , "", .
  • a.
  • "world" ?

? , " " .

+4
4

, :

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

, new .

, (. ). , ( ). : String Char .NET?

+1

, a += "world"; , , a = a + "world";.

+=, . , ?

+1

a += "world", a = a + "world", a "world", a.

+1

When you execute a+="World", it creates a new line with a value a + "world". Since helloit is still in use b, it is not yet garbage collected.

0
source

Source: https://habr.com/ru/post/1536657/


All Articles