Search code examples
.netstringclone

When (deep) Cloning, use String.Copy or str1 = str2?


When (deep) Cloning a custom object, should I use clone.str1 = String.Copy(obj.str1) or clone.str1 = obj.str1?

I'd prefer the latter - shorter and quicker, but is it "safe"?

I'd point to this thread, but, however, not sure what to use.


Solution

  • Yes - the latter choice (simple assignment) is safe for strings (in managed code), as this code illustrates:

        string s1 = "Initial Value";
        string s2 = s1;
    
        Console.WriteLine("String1: " + s1);
        Console.WriteLine("String2: " + s2);
    
        s1 = "New Value";
    
        Console.WriteLine("String1 - after change: " + s1);
        Console.WriteLine("String2 - after change: " + s2);
    

    Output:

    String1: Initial Value
    String2: Initial Value
    String1 - after change: New Value
    String2 - after change: Initial Value
    

    Strings are immutable - so when you change s1, you are really creating a new string and assigning it. The reference of s2 remains pointing to the old instance.