views:

215

answers:

3

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?

+11  A: 

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.

stusmith
So when I change the string in the copy object, a new string is created w/ a new reference? So when I make something like oldString = oldString + "A", I'm creating a new object with a new reference?
danmine
...this also explains why String.Replace has to return a new string, rather than changing the string.
stusmith
If you need a mutable string, consider using StringBuilder.
stusmith
I learn something new everyday. That explains a lot of questions I had w/ strings.
danmine
+4  A: 

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.

Marc Gravell
+4  A: 

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.

Jon Skeet