Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can also achieve this without cloneable interface by using binary formatter: NOTE: ALL classes as part of the object graph must be marked Serializable. </p> <pre><code>void Main() { var student1=new Student{Name="Bob"}; var student2=new Student{Name="Jim"}; var lstStudent=new List&lt;Student&gt;(); lstStudent.Add(student1); lstStudent.Add(student2); var lstCopy=new List&lt;Student&gt;(lstStudent); var clone=Clone(lstStudent); student1.Name="JOE"; lstCopy.Dump(); lstStudent.Dump(); clone.Dump(); } public List&lt;Student&gt; Clone(List&lt;Student&gt; source) { BinaryFormatter bf=new BinaryFormatter(); using(var ms=new MemoryStream()) { bf.Serialize(ms,source); ms.Seek(0,0); return (List&lt;Student&gt;)bf.Deserialize(ms); } } [Serializable] public class Student { public string Name { get; set; } } </code></pre> <p>OUTPUT:</p> <pre><code>5List&lt;Student&gt; (2 items) 4 Name JOE Jim 5List&lt;Student&gt; (2 items) 4 Name JOE Jim 5List&lt;Student&gt; (2 items) 4 Name Bob Jim </code></pre> <p>code is formatted for dumping into LINQPad</p> <p>EDIT: This is an option in situations where it's not possible to implement <code>ICloneable</code>. When applicable, code to interfaces. In other words, you can implement <code>ICloneable</code> on the student object and use the <code>BinaryFormatter</code> logic in the <code>Clone()</code> method; However, As a developer, you have the option to decide for yourself what you want to do. Options are not necessarily advice and advice isn't always an option. There are times when you must do what it takes to complete a task and that's where options come into play.</p> <p>This is a pretty widely accepted, deep cloning, method: <a href="https://stackoverflow.com/questions/129389/how-do-you-do-a-deep-copy-an-object-in-net-c-specifically">How do you do a deep copy of an object in .NET (C# specifically)?</a></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