Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Shallow Copying Class Objects vs. String Variables

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Note: I did check previously asked questions, and I could not find a similar question.

>Solution :

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:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading