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.
Person person2 = person1; // Shallow copy<-- This is not a "shallow copy" - that's a reference-copy. A shallow-copy would require anew Personthen copying all properties over (though only 1 level-deep, if it were 2+ levels it would be some kind of deep-copy).reference copyingon the internet and how exactly it differs from shallow and deep copying. Maybe the world really needs a medium blog post from one of you guys. This information seems so obscure to me