C # Special string reference type

Source: Internet
Author: User

The. Net Framework Program Design (revision) has the following description: The String type directly inherits from the Object, which makes it a reference type. That is to say, the stack on the thread does not reside with any strings. Note that "direct inheritance" here ". Directly inherited from the Object type must be the reference type, because all value types inherit from System. ValueType. It is worth noting that System. ValueType is a reference type ).

I:

 

 string str1 = "string"; 
string str2 = "string"; Console.WriteLine(string.ReferenceEquals(str1, str2));

 

 

Since the String type is a reference type, the output of code 1 should be False, but in fact the output of code 1 is True.

In fact, this is the automatic optimization function of the String type. Str1 and str2 reference the same object to save memory and do not open up memory space for str2. CLR uses a technology called string resident. During CLR initialization, an internal hash is created. The key is a string and the value is a reference to the string in the managed heap. At the beginning, the hash is empty. During JIT compiler compilation, every text constant string is searched in the hash. The "abc" string is first searched because it is not found, the compiler constructs a New String object reference pointing to "abc" in the managed heap, and then adds the "abc" String and reference pointing to this object to the hash list. Next, find the second "abc" in the hash list. Because the String is found this time, the reference pointing to the same String object will be saved in the str2 variable, str1 and str2 point to the same reference, so string. referenceEquals (str1, str2) returns true.

In addition, C # does not allow the use of the new operator to create a String object. The Compiler reports an error.

 

II:

 

static void Main(string[] args) { 
  string str = "string";   Change(str);   Console.WriteLine(str); } static void Change(string str) {   str = "Changed"; }

The parameter passed by the method is the copy of the original content, and the process can be expressed:

 

Statement str = "Changed"

  

Statement str = "Changed"

  

In this way, we can see that the original String object does not change str = "Changed" but only creates a new String object (other reference types are to change the value pointed to by memory address 1 ), therefore, the ref or out modifier must be added to the parameters of this method. Therefore, we can also conclude that a string has a constant, that is, once a string is created, we can no longer extend, shorten, or change any character in it.

As explained in MSDN, string objects cannot be changed once they are created. The method for string operations actually returns a New String object.

In another case, the string operation has the value type feature: str1 = str2, only compares the value, not the address (due to the overwrite of the = Operator in MS ).

 

 III:

The String object cannot be changed. Every time you use a method in the System. String class, you must create a new String object in the memory, which requires a new space for the new object. If you need to modify the String repeatedly, the system overhead associated with creating a new String object may be very expensive. If you want to modify the string without creating a new object, you can use the System. Text. StringBuilder class. For example, when many strings are connected together in a loop, using the StringBuilder class can improve performance.

The following is a simple example:

 

 namespace TCP
{
public class Program
{     public class User
      {
          private string _name;
          private string _age;
          public User(string name, string age)
          {
              _name = name;
              _age = age;
          }

          public string name
          {
              get { return _name; }
              set { _name = value; }
          }
          public string age
          {
              get { return _age; }
              set { _age = value; }
          }
      }
   }

   public static void editUser(User user, StringBuilder str,string code)
   {
     code = "VB.NET";
     str = str.Remove(0, 1);
     str.Append("E");
     user.name = "LEE";
user.age = "10";
}
  
static void Main(string[] args)
   {
     string code = "C#";
   User user = new User("Li","23");
     StringBuilder str = new StringBuilder();            
     str.Append("A");            
     editUser(user, str,code);

     Console.WriteLine(code);
     Console.WriteLine(str);
     Console.WriteLine(user.name);
     Console.WriteLine(user.age);
     Console.ReadLine();

   }}

 

The above code is as follows:

 

  

From the above we can see that the value of the string type has not changed, and the value of StringBuilder and class has changed.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.