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.