Analyze problems
By viewing the metadata of the system. string type, you can see that system. string is a subclass directly inherited from system. object. As described in the previous sections, all types that directly or indirectly inherit from system. valuetype belong to the value type. Therefore, system. string belongs to the reference type rather than the value type. However, some features of string may lead to the illusion that string belongs to the value type. The following code demonstrates these features.
Using System; Namespace Test { Class Stringattribute { Static Void Main (){ String A = " I am a string. " ; String B = A; console. writeline ( Object . Referenceequals (a, B )); // Try to use reference B to modify the object pointed to by B = " I am a new string. " ; Console. writeline (a); console. writeline (B); console. writeline ( Object . Referenceequals (A, B); console. Read ();}}}
After analyzing the code above, the program starts to declare two string references and points them to the same string object. This can be verified by calling the object. referenceequals method. The following code view modifies the object content by referencing B: B = "I am a new string. "; but this attempt failed. The objects A and B respectively looked at and found that they point to different object instances, and called the object. the referenceequals method finds that the two references do not point to the same object any more. The following is the code execution result.
This execution result is easy to give people the illusion that the string belongs to the value type. In fact, this is because the character string object cannot be modified. Once the string object is initialized, it cannot be modified, including deleting, cutting, and inserting. It is a read-only object. In the above Code, B = "I am a new string. "; actually, A New String object is initialized and assigned to B's reference, which explains the execution result of the above Code.
Due to the read-only feature of the string, any modification to the string object will generate a new String object. Understanding this is very important. When writing code, you should try to avoid generating too many variable objects in the string without any need. This will be detailed in the following sections.
Answer
String is a reference type object. Its object cannot be modified after initialization. Any attempt to modify the string will generate a new String object.