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

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

I would prefer the latter - shorter and faster, but is it safe?

I would point to this thread , but, however, am not sure what to use.

+3
source share
4 answers

Yes - the last 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);

Conclusion:

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

Lines are immutable - so when you change s1, you really create a new line and assign it. The s2 link remains a pointer to the old instance.

+10

String.Copy .
, .

+3

, BinaryFormatter?

.

, :

public Automobile Clone()
{
    Automobile result = null;
    using (MemoryStream ms = new MemoryStream())
    {
         BinaryFormatter bf = new BinaryFormatter();
         bf.Serialize(ms, this);
         ms.Position = 0;
         result = (Automobile)bf.Deserialize(ms);
     }
     return result;
}
+1

. .NET, , .

edit: ... , , , .

+1

Source: https://habr.com/ru/post/1734415/


All Articles