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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes – the latter choice (simple assignment) is safe for strings (in managed code), as this code illustrates:
Output:
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.