string a = "John";
string b = "Doe";
a = b; // Shallow copying strings
b = "Elon Musk";
Console.WriteLine(a); // Output: Doe
This prints "Doe", meaning the change in one variable is NOT reflected to the other variable. However, when "boxing in" the string property into a class and performing a shallow copy with class objects, the change in one object is actually reflected to the other object.
public class Person
{
public string Name { get; set; }
}
// ----
Person person1 = new Person { Name = "John" };
Person person2 = person1; // Shallow copy
Console.WriteLine(person1.Name); // Output: John
Console.WriteLine(person2.Name); // Output: John
person2.Name = "Jane"; // Modifying the property via person2
Console.WriteLine(person1.Name); // Output: Jane (changes are reflected in person1)
Console.WriteLine(person2.Name); // Output: Jane
I am trying to understand what the reason is that the changes are reflected in 2nd case, but not reflected in 1st case. Both class objects and string type are reference-type, therefore, the change should be reflected in the 1st case too, right? Please help me understand what the difference between the two cases that is causing this difference in behavior.
I know that string type is immutable. Are class objects mutable? Is that the reason for the difference between two cases?
Note: I did check previously asked questions, and I could not find a similar question.
string
is a reference type (immutable one but still), local variables store reference to some memory occupied by it, even if string was mutable b = "Elon Musk";
does not change the data stored by reference in b
it changes the reference itself to a completely new one, i.e. for person sample equivalent would be:
Person person1 = new Person { Name = "John" };
Person person2 = person1;
person2 = new Person { Name = "Elon Musk" };
With corresponding effect on the result.
Read more: