Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do strings work when shallow copying something in C#?

Tags:

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?

like image 447
danmine Avatar asked Feb 03 '09 10:02

danmine


People also ask

What is shallow copy in C?

A shallow copy in this particular context means that you copy "references" (pointers, whatever) to objects, and the backing store of these references or pointers is identical, it's the very same object at the same memory location. A deep copy, in contrast, means that you copy an entire object (struct).

What does a shallow copy do?

A shallow copy creates a new object which stores the reference of the original elements. So, a shallow copy doesn't create a copy of nested objects, instead it just copies the reference of nested objects. This means, a copy process does not recurse or create copies of nested objects itself.

What is the difference between deep copy and shallow copy in C?

Shallow Copy stores the references of objects to the original memory address. Deep copy stores copies of the object's value. Shallow Copy reflects changes made to the new/copied object in the original object. Deep copy doesn't reflect changes made to the new/copied object in the original object.


2 Answers

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.

like image 126
stusmith Avatar answered Sep 22 '22 01:09

stusmith


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.

like image 40
Jon Skeet Avatar answered Sep 23 '22 01:09

Jon Skeet