Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You might check out the protected <a href="http://msdn.microsoft.com/en-us/library/system.object.memberwiseclone.aspx" rel="nofollow">object.MemberwiseClone</a> method. This method has been around since the early days.</p> <pre><code>void Main() { Profile p = new Profile("bob", @"c:\foo"); p.FileList.Add("bar.txt"); Profile copy = p.DeepCopy(); copy.FileList.Clear(); copy.FileList.Add("baz.log"); p.Dump("p"); copy.Dump("copy"); } public class Profile { public Profile(string name, string targetPath) { this.Name = name; this.TargetPath = targetPath; this.FileList = new List&lt;string&gt;(); } public Profile DeepCopy() { Profile copy = (Profile)this.MemberwiseClone(); // this takes care of Name &amp; TargetPath copy.FileList = new List&lt;string&gt;(this.FileList); return copy; } public string Name { get; private set; } public string TargetPath { get; private set; } public List&lt;string&gt; FileList { get; private set; } } </code></pre> <p>You can think of <code>MemberwiseClone</code> as making a shallow bitwise copy. This is generally okay for value-types like int, double, float and even for immutable reference types like string. However, you'll want to make copies of mutable reference types like <code>List&lt;string&gt;</code> in the profile class so that mutations of the copy don't also change the original. It's kind of a fine-line in terms of maintenance - if you add a new mutable property, you have to remember to make a copy in the deep-copy method after the cloning happens.</p> <p>Depending on your design, there could be other things like event registrations that you might not want copied. You can think of these as transients. You need to be cautious too if your app is multi-threaded, you will have to take the same pains during your copy that you do in other places to maintain your object's integrity (for example taking locks.)</p> <p>I don't have performance numbers. Regardless, whatever advice you take, you're best suited to do some performance tests of your own to see if it's fast-enough.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload