Immutability of the string type in C #

Source: Internet
Author: User

Today, my colleague asked me a question:

static void Main(string[] args)        {            People people1 = new People();            people1.Name = "BeforePeopleChange";            string str = "BeforeStringChange";            ChangeString(str);            ChangePeople(people1);            Console.WriteLine(people1.Name);            Console.WriteLine(str);                        Console.ReadKey();        }        public sealed class People        {            public string Name { get; set; }        }        public static void ChangeString(string str)        {            str = "AfterStringChange";        }        public static void ChangePeople(People model)        {            model.Name = "AfterPeopleChange";        }        

The running result is as follows:

The problem is that the string and people are both reference types. Why do we modify their values in another method? The string remains unchanged and the people changes.

 

In fact, the string type is the primitive type in C #. It is a special reference type and is immutable. Therefore, changing the str value in the changestring method will re-create a memory in the managed heap and save the modified value to the newly created memory. People is only a common reference type. The changepeople method directly modifies the memory referenced by people1, so this problem occurs.

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.