Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You've done an addition AND an assignment in one step. Strings are immutable, but also a reference type.</p> <pre><code>string b = "h"; b = b + "ello"; </code></pre> <p>We can look at the pseudo-memory like this:</p> <pre><code>string b = "h"; // b := 0x00001000 ["h"] string tmp1 = "ello"; // tmp1 := 0x00002000 ["ello"] string tmp2 = b + tmp1; // tmp2 := 0x00003000 ["hello"] string b = tmp2; // b := 0x00003000 ["hello"] </code></pre> <p>I'm not entirely sure where you're getting that text, because as I read the documentation for the <a href="http://msdn.microsoft.com/en-us/library/362314fe.aspx" rel="nofollow noreferrer">string</a> class I find (not that I think "h" actually gets garbage collected):</p> <blockquote> <p>Strings are immutable--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and that new object is assigned to b. The string "h" is then eligible for garbage collection.</p> </blockquote> <p>@Jon Skeet brings up that "h" will never be garbage collected due to string interning, and I agree with him, but even moreso the C# Standard agrees with him, otherwise the following from §2.4.4.5 String literals could not be true:</p> <blockquote> <p>Each string literal does not necessarily result in a new string instance. When two or more string literals that are equivalent according to the string equality operator (§7.9.7) appear in the same program, these string literals refer to the same string instance. </p> </blockquote>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload