General and special character strings
String is one of the primitive types of C #. It is a reference type, corresponding to the System. String type in FCL. What are the similarities and differences between the string type and the common reference type?
1. The character String is fixed and immutable. The character String exists in the System. String namespace. We can see through the decompilation tool:
There are only two read-only attributes in the string, and there are no configurable attributes. Therefore, string type instances have fixed immutability. As long as the content of the string is changed, the system will generate a brand new string in the heap memory. In fact, this is not counted as the special nature of the string, which is no different from the common reference type, but the string type does not create writable attributes during definition, therefore, this can only be regarded as a general character of a string.
The Demo code is as follows:
1 class Program 2 {3 static void Main (string [] args) 4 {5 string str1 = "Hi"; 6 string str2 = str1; 7 str2 = "Hello "; // this operation is equivalent to re-creating an instance 8 9 Console for instance str2. writeLine ("str1 value: {0}", str1); 10 Console. writeLine ("str2 value: {0}", str2); 11 Console. readKey (); 12} 13}
The running result is as follows:
2. The concept of resident pool in a string, which is unique to the string type, so this is the particularity of the string. When the declared string is the same as the value of an existing string in the heap, no space will be opened in the heap to create a new instance, instead, point the reference of the currently declared string to an existing instance.