Strings are considered reference types yet can act like values. When shallow copying something either manually or with the MemberwiseClone(), how are strings handled? Are they considred separate and isolated from the copy and master?
Strings ARE reference types. However they are immutable (they cannot be changed), so it wouldn't really matter if they copied by value, or copied by reference.
If they are shallow-copied then the reference will be copied... but you can't change them so you can't affect two objects at once.
Consider this:
public class Person
{
string name;
// Other stuff
}
If you call MemberwiseClone, you'll end up with two separate instances of Person, but their name
variables, while distinct, will have the same value - they'll refer to the same string instance. This is because it's a shallow clone.
If you change the name in one of those instances, that won't affect the other, because the two variables themselves are separate - you're just changing the value of one of them to refer to a different string.
You are only copying a reference (think "pointer"); the two references are separate (but happen to have the same value), but there is only a single string object.
@stusmith has a really good answer, and jon mentions the behavior of a shallow copy. Just to elaborate on this I made a .NET Fiddle
You'll notice that I make a shallow copy, but really, since the only member is a string, is functions as a deep copy as well. To be clear, it IS NOT a deep copy in the sense that the reference to the string is duplicated, so when the copy function is ran, there exist two objects with references to the same string in memory.
However for many applications, this is fine because, like in my example, when I update the string after copying the first object, a new string and reference are created, and so the end result is two objects with different references to different string values.
Here is a preview of what the fiddle is doing:
// Create a person
Person a = new Person("Sally");
// Shallow copy the person
Person b = a.ShallowCopy();
// Change the name of the second person
b.firstName = "Bob";
// Observe that the original person's name has not changed
Console.WriteLine("First person is {0}", a.firstName);
Console.WriteLine("Second person is {0}", b.firstName);
// Output is:
// First person is Sally
// Second person is Bob
© 2022 - 2024 — McMap. All rights reserved.