First, preface
When I first touched C #, the book said that string is a special type of reference, so the string type variable is passed as a parameter to another method, the value of the original variable will not change after being modified, when I look at the face of a crazy, what is called Special .... Later I heard that the string is immutable (immutable), which means that the string cannot be changed once it is created. Find out today what is special in particular, by using the VS time window to view the variable stack address (&variablename).
Second, string characteristics
- string of reference type
As we all know in C #, the reference type is allocated on the heap, the value type is allocated on the stack, but the address of the reference type is allocated on the stack. String as a "special" reference type, and not because of its particularity, it is allocated to the stack, it is still on the heap.
- String pool
When the compiler compiles the source code, the literal string is embedded in the metadata of the managed module, in order to reduce the size of the file, the compiler writes the string only once in the module metadata, all of which refer to the same location, so there is only one instance of the same literal string in a program .
- string retention
As mentioned earlier, there is only one instance of a literal string with the same program, and there is only one instance of the non-literal string?
As can be seen, the same non-literal string heap address is not the same, if you want to exist only one copy through the staging pool (if the application does not maintain a reference to the original string, the GC can release the memory of that string), see NSDN:String.Intern
- Non-variability of strings
The string is immutable and creates a new instance if a change occurs. As can be seen, the variable str is prefixed with the literal string "a" and the heap address that the variable str points to has changed.
- A "special" string
A string is a "special" reference type that does not change the original string after it has been modified as a parameter
As can be seen, strvalue and Mstrvalue's heap address is consistent, that is, the string parameter is the same as the normal reference type of the argument is the same, is the incoming reference address. So the problem is, since the address has been passed in, why the string modified after the original string does not change it? The reason is that the string is immutable, and when the value of the string variable in the method changes, the string variable will point to a new address, the value of the original address is not changed, so the value of the original string does not change.
Explore C # Strings