<p>I want to do something like:</p>

<pre><code>MyObject myObj = GetMyObj(); // Create and fill a new object
MyObject newObj = myObj.Clone();
</code></pre>

<p>And then make changes to the new object that are not reflected in the original object.</p>

<p>I don't often need this functionality, so when it's been necessary, I've resorted to creating a new object and then copying each property individually, but it always leaves me with the feeling that there is a better or more elegant way of handling the situation.</p>

<p>How can I clone or deep copy an object so that the cloned object can be modified without any changes being reflected in the original object?</p>

[{'answer_id': 78552, 'author': 'HappyDude', 'author_id': 14266, 'author_profile': 'https://Stackoverflow.com/users/14266', 'pm_score': 4, 'selected': False, 'text': '<p>In general, you implement the ICloneable interface and implement Clone yourself.\nC# objects have a built-in MemberwiseClone method that performs a shallow copy that can help you out for all the primitives.</p>\n\n<p>For a deep copy, there is no way it can know how to automatically do it.</p>\n'}, {'answer_id': 78568, 'author': 'dimarzionist', 'author_id': 10778, 'author_profile': 'https://Stackoverflow.com/users/10778', 'pm_score': 5, 'selected': False, 'text': "<ol>\n<li>Basically you need to implement ICloneable interface and then realize object structure copying. </li>\n<li>If it's deep copy of all members, you need to insure (not relating on solution you choose) that all children are clonable as well. </li>\n<li>Sometimes you need to be aware of some restriction during this process, for example if you copying the ORM objects most of frameworks allow only one object attached to the session and you MUST NOT make clones of this object, or if it's possible you need to care about session attaching of these objects.</li>\n</ol>\n\n<p>Cheers.</p>\n"}, {'answer_id': 78577, 'author': 'Nick', 'author_id': 1490, 'author_profile': 'https://Stackoverflow.com/users/1490', 'pm_score': 7, 'selected': False, 'text': '<p>I prefer a copy constructor to a clone. The intent is clearer.</p>\n'}, {'answer_id': 78587, 'author': 'Zach Burlingame', 'author_id': 2233, 'author_profile': 'https://Stackoverflow.com/users/2233', 'pm_score': 5, 'selected': False, 'text': '<p>The short answer is you inherit from the ICloneable interface and then implement the .clone function. Clone should do a memberwise copy and perform a deep copy on any member that requires it, then return the resulting object. This is a recursive operation ( it requires that all members of the class you want to clone are either value types or implement ICloneable and that their members are either value types or implement ICloneable, and so on).</p>\n\n<p>For a more detailed explanation on Cloning using ICloneable, check out <a href="https://web.archive.org/web/20120113123300/http://www.ondotnet.com/pub/a/dotnet/2002/11/25/copying.html" rel="noreferrer">this article</a>.</p>\n\n<p>The <em>long</em> answer is "it depends". As mentioned by others, ICloneable is not supported by generics, requires special considerations for circular class references, and is actually viewed by some as a <a href="http://blogs.msdn.com/brada/archive/2004/05/03/125427.aspx" rel="noreferrer">"mistake"</a> in the .NET Framework. The serialization method depends on your objects being serializable, which they may not be and you may have no control over. There is still much debate in the community over which is the "best" practice. In reality, none of the solutions are the one-size fits all best practice for all situations like ICloneable was originally interpreted to be.</p>\n\n<p>See the this <a href="http://developerscon.blogspot.com/2008/06/c-object-clone-wars.html" rel="noreferrer">Developer\'s Corner article</a> for a few more options (credit to Ian).</p>\n'}, {'answer_id': 78612, 'author': 'johnc', 'author_id': 5302, 'author_profile': 'https://Stackoverflow.com/users/5302', 'pm_score': 12, 'selected': True, 'text': '<p>Whereas one approach is to implement the <a href="http://msdn.microsoft.com/en-us/library/system.icloneable.aspx" rel="noreferrer"><code>ICloneable</code></a> interface (described <a href="https://stackoverflow.com/questions/78536/cloning-objects-in-c/78568#78568">here</a>, so I won\'t regurgitate), here\'s a nice deep clone object copier I found on <a href="http://www.codeproject.com/Articles/23832/Implementing-Deep-Cloning-via-Serializing-objects" rel="noreferrer">The Code Project</a> a while ago and incorporated it into our code.\nAs mentioned elsewhere, it requires your objects to be serializable.</p>\n<pre><code>using System;\nusing System.IO;\nusing System.Runtime.Serialization;\nusing System.Runtime.Serialization.Formatters.Binary;\n\n/// &lt;summary&gt;\n/// Reference Article http://www.codeproject.com/KB/tips/SerializedObjectCloner.aspx\n/// Provides a method for performing a deep copy of an object.\n/// Binary Serialization is used to perform the copy.\n/// &lt;/summary&gt;\npublic static class ObjectCopier\n{\n    /// &lt;summary&gt;\n    /// Perform a deep copy of the object via serialization.\n    /// &lt;/summary&gt;\n    /// &lt;typeparam name=&quot;T&quot;&gt;The type of object being copied.&lt;/typeparam&gt;\n    /// &lt;param name=&quot;source&quot;&gt;The object instance to copy.&lt;/param&gt;\n    /// &lt;returns&gt;A deep copy of the object.&lt;/returns&gt;\n    public static T Clone&lt;T&gt;(T source)\n    {\n        if (!typeof(T).IsSerializable)\n        {\n            throw new ArgumentException(&quot;The type must be serializable.&quot;, nameof(source));\n        }\n\n        // Don\'t serialize a null object, simply return the default for that object\n        if (ReferenceEquals(source, null)) return default;\n\n        using var Stream stream = new MemoryStream();\n        IFormatter formatter = new BinaryFormatter();\n        formatter.Serialize(stream, source);\n        stream.Seek(0, SeekOrigin.Begin);\n        return (T)formatter.Deserialize(stream);\n    }\n}\n</code></pre>\n<p>The idea is that it serializes your object and then deserializes it into a fresh object. The benefit is that you don\'t have to concern yourself about cloning everything when an object gets too complex.</p>\n<p>In case of you prefer to use the new <a href="http://en.wikipedia.org/wiki/Extension_method" rel="noreferrer">extension methods</a> of C# 3.0, change the method to have the following signature:</p>\n<pre><code>public static T Clone&lt;T&gt;(this T source)\n{\n   // ...\n}\n</code></pre>\n<p>Now the method call simply becomes <code>objectBeingCloned.Clone();</code>.</p>\n<p><strong>EDIT</strong> (January 10 2015) Thought I\'d revisit this, to mention I recently started using (Newtonsoft) Json to do this, it <a href="http://maxondev.com/serialization-performance-comparison-c-net-formats-frameworks-xmldatacontractserializer-xmlserializer-binaryformatter-json-newtonsoft-servicestack-text/" rel="noreferrer">should be</a> lighter, and avoids the overhead of [Serializable] tags. (<strong>NB</strong> @atconway has pointed out in the comments that private members are not cloned using the JSON method)</p>\n<pre><code>/// &lt;summary&gt;\n/// Perform a deep Copy of the object, using Json as a serialization method. NOTE: Private members are not cloned using this method.\n/// &lt;/summary&gt;\n/// &lt;typeparam name=&quot;T&quot;&gt;The type of object being copied.&lt;/typeparam&gt;\n/// &lt;param name=&quot;source&quot;&gt;The object instance to copy.&lt;/param&gt;\n/// &lt;returns&gt;The copied object.&lt;/returns&gt;\npublic static T CloneJson&lt;T&gt;(this T source)\n{            \n    // Don\'t serialize a null object, simply return the default for that object\n    if (ReferenceEquals(source, null)) return default;\n\n    // initialize inner objects individually\n    // for example in default constructor some list property initialized with some values,\n    // but in \'source\' these items are cleaned -\n    // without ObjectCreationHandling.Replace default constructor values will be added to result\n    var deserializeSettings = new JsonSerializerSettings {ObjectCreationHandling = ObjectCreationHandling.Replace};\n\n    return JsonConvert.DeserializeObject&lt;T&gt;(JsonConvert.SerializeObject(source), deserializeSettings);\n}\n</code></pre>\n'}, {'answer_id': 78856, 'author': 'Ryan Lundy', 'author_id': 5486, 'author_profile': 'https://Stackoverflow.com/users/5486', 'pm_score': 8, 'selected': False, 'text': '<p>The reason not to use <a href="http://referencesource.microsoft.com/mscorlib/system/icloneable.cs.html#fb795e239ce05299" rel="nofollow noreferrer">ICloneable</a> is <strong>not</strong> because it doesn\'t have a generic interface.  <a href="https://learn.microsoft.com/en-us/archive/blogs/brada/should-we-obsolete-icloneable-the-slar-on-system-icloneable" rel="nofollow noreferrer">The reason not to use it is because it\'s vague</a>.  It doesn\'t make clear whether you\'re getting a shallow or a deep copy; that\'s up to the implementer.</p>\n<p>Yes, <code>MemberwiseClone</code> makes a shallow copy, but the opposite of <code>MemberwiseClone</code> isn\'t <code>Clone</code>; it would be, perhaps, <code>DeepClone</code>, which doesn\'t exist.  When you use an object through its ICloneable interface, you can\'t know which kind of cloning the underlying object performs.  (And XML comments won\'t make it clear, because you\'ll get the interface comments rather than the ones on the object\'s Clone method.)</p>\n<p>What I usually do is simply make a <code>Copy</code> method that does exactly what I want.</p>\n'}, {'answer_id': 1497125, 'author': 'Daniel Mošmondor', 'author_id': 166251, 'author_profile': 'https://Stackoverflow.com/users/166251', 'pm_score': 4, 'selected': False, 'text': '<p>I came up with this to overcome a <a href="http://en.wikipedia.org/wiki/.NET_Framework" rel="noreferrer">.NET</a> shortcoming having to manually deep copy List&lt;T>.</p>\n\n<p>I use this:</p>\n\n<pre><code>static public IEnumerable&lt;SpotPlacement&gt; CloneList(List&lt;SpotPlacement&gt; spotPlacements)\n{\n    foreach (SpotPlacement sp in spotPlacements)\n    {\n        yield return (SpotPlacement)sp.Clone();\n    }\n}\n</code></pre>\n\n<p>And at another place:</p>\n\n<pre><code>public object Clone()\n{\n    OrderItem newOrderItem = new OrderItem();\n    ...\n    newOrderItem._exactPlacements.AddRange(SpotPlacement.CloneList(_exactPlacements));\n    ...\n    return newOrderItem;\n}\n</code></pre>\n\n<p>I tried to come up with oneliner that does this, but it\'s not possible, due to yield not working inside anonymous method blocks.</p>\n\n<p>Better still, use generic List&lt;T> cloner:</p>\n\n<pre><code>class Utility&lt;T&gt; where T : ICloneable\n{\n    static public IEnumerable&lt;T&gt; CloneList(List&lt;T&gt; tl)\n    {\n        foreach (T t in tl)\n        {\n            yield return (T)t.Clone();\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 1834578, 'author': 'Michael White', 'author_id': 223103, 'author_profile': 'https://Stackoverflow.com/users/223103', 'pm_score': 5, 'selected': False, 'text': '<p>Well I was having problems using ICloneable in Silverlight, but I liked the idea of seralization, I can seralize XML, so I did this:</p>\n<pre><code>static public class SerializeHelper\n{\n    //Michael White, Holly Springs Consulting, 2009\n    //michael@hollyspringsconsulting.com\n    public static T DeserializeXML&lt;T&gt;(string xmlData) \n        where T:new()\n    {\n        if (string.IsNullOrEmpty(xmlData))\n            return default(T);\n\n        TextReader tr = new StringReader(xmlData);\n        T DocItms = new T();\n        XmlSerializer xms = new XmlSerializer(DocItms.GetType());\n        DocItms = (T)xms.Deserialize(tr);\n\n        return DocItms == null ? default(T) : DocItms;\n    }\n\n    public static string SeralizeObjectToXML&lt;T&gt;(T xmlObject)\n    {\n        StringBuilder sbTR = new StringBuilder();\n        XmlSerializer xmsTR = new XmlSerializer(xmlObject.GetType());\n        XmlWriterSettings xwsTR = new XmlWriterSettings();\n        \n        XmlWriter xmwTR = XmlWriter.Create(sbTR, xwsTR);\n        xmsTR.Serialize(xmwTR,xmlObject);\n        \n        return sbTR.ToString();\n    }\n\n    public static T CloneObject&lt;T&gt;(T objClone) \n        where T:new()\n    {\n        string GetString = SerializeHelper.SeralizeObjectToXML&lt;T&gt;(objClone);\n        return SerializeHelper.DeserializeXML&lt;T&gt;(GetString);\n    }\n}\n</code></pre>\n'}, {'answer_id': 3968577, 'author': 'xr280xr', 'author_id': 263832, 'author_profile': 'https://Stackoverflow.com/users/263832', 'pm_score': 3, 'selected': False, 'text': "<p>I've seen it implemented through reflection as well. Basically there was a method that would iterate through the members of an object and appropriately copy them to the new object. When it reached reference types or collections I think it did a recursive call on itself. Reflection is expensive, but it worked pretty well.</p>\n"}, {'answer_id': 5324679, 'author': 'Konstantin Salavatov', 'author_id': 204647, 'author_profile': 'https://Stackoverflow.com/users/204647', 'pm_score': 6, 'selected': False, 'text': '<p>Simple extension method to copy all the public properties. Works for any objects and <strong>does not</strong> require class to be <code>[Serializable]</code>. Can be extended for other access level.</p>\n\n<pre><code>public static void CopyTo( this object S, object T )\n{\n    foreach( var pS in S.GetType().GetProperties() )\n    {\n        foreach( var pT in T.GetType().GetProperties() )\n        {\n            if( pT.Name != pS.Name ) continue;\n            ( pT.GetSetMethod() ).Invoke( T, new object[] \n            { pS.GetGetMethod().Invoke( S, null ) } );\n        }\n    };\n}\n</code></pre>\n'}, {'answer_id': 7316457, 'author': 'dougajmcdonald', 'author_id': 777733, 'author_profile': 'https://Stackoverflow.com/users/777733', 'pm_score': 3, 'selected': False, 'text': "<p>Here is a deep copy implementation:</p>\n\n<pre><code>public static object CloneObject(object opSource)\n{\n    //grab the type and create a new instance of that type\n    Type opSourceType = opSource.GetType();\n    object opTarget = CreateInstanceOfType(opSourceType);\n\n    //grab the properties\n    PropertyInfo[] opPropertyInfo = opSourceType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);\n\n    //iterate over the properties and if it has a 'set' method assign it from the source TO the target\n    foreach (PropertyInfo item in opPropertyInfo)\n    {\n        if (item.CanWrite)\n        {\n            //value types can simply be 'set'\n            if (item.PropertyType.IsValueType || item.PropertyType.IsEnum || item.PropertyType.Equals(typeof(System.String)))\n            {\n                item.SetValue(opTarget, item.GetValue(opSource, null), null);\n            }\n            //object/complex types need to recursively call this method until the end of the tree is reached\n            else\n            {\n                object opPropertyValue = item.GetValue(opSource, null);\n                if (opPropertyValue == null)\n                {\n                    item.SetValue(opTarget, null, null);\n                }\n                else\n                {\n                    item.SetValue(opTarget, CloneObject(opPropertyValue), null);\n                }\n            }\n        }\n    }\n    //return the new item\n    return opTarget;\n}\n</code></pre>\n"}, {'answer_id': 8422769, 'author': 'supercat', 'author_id': 363751, 'author_profile': 'https://Stackoverflow.com/users/363751', 'pm_score': 3, 'selected': False, 'text': "<p>Follow these steps:</p>\n\n<ul>\n<li>Define an <code>ISelf&lt;T&gt;</code> with a read-only <code>Self</code> property that returns <code>T</code>, and <code>ICloneable&lt;out T&gt;</code>, which derives from <code>ISelf&lt;T&gt;</code> and includes a method <code>T Clone()</code>.</li>\n<li>Then define a <code>CloneBase</code> type which implements a <code>protected virtual generic VirtualClone</code> casting <code>MemberwiseClone</code> to the passed-in type.  </li>\n<li>Each derived type should implement <code>VirtualClone</code> by calling the base clone method and then doing whatever needs to be done to properly clone those aspects of the derived type which the parent VirtualClone method hasn't yet handled.</li>\n</ul>\n\n<p>For maximum inheritance versatility, classes exposing public cloning functionality should be <code>sealed</code>, but derive from a base class which is otherwise identical except for the lack of cloning.  Rather than passing variables of the explicit clonable type, take a parameter of type <code>ICloneable&lt;theNonCloneableType&gt;</code>.  This will allow a routine that expects a cloneable derivative of  <code>Foo</code> to work with a cloneable derivative of <code>DerivedFoo</code>, but also allow the creation of non-cloneable derivatives of <code>Foo</code>.</p>\n"}, {'answer_id': 12609692, 'author': 'cregox', 'author_id': 274502, 'author_profile': 'https://Stackoverflow.com/users/274502', 'pm_score': 7, 'selected': False, 'text': '<p>After much much reading about many of the options linked here, and possible solutions for this issue, I believe <a href="https://developerscon.blogspot.com/2008/06/c-object-clone-wars.html" rel="noreferrer">all the options are summarized pretty well at <em>Ian P</em>\'s link</a> (all other options are variations of those) and the best solution is provided by <a href="http://www.agiledeveloper.com/articles/cloning072002.htm" rel="noreferrer"><em>Pedro77</em>\'s link</a> on the question comments.</p>\n\n<p>So I\'ll just copy relevant parts of those 2 references here. That way we can have:</p>\n\n<h2>The best thing to do for cloning objects in C sharp!</h2>\n\n<p>First and foremost, those are all our options:</p>\n\n<ul>\n<li>Manually with <strong><a href="https://learn.microsoft.com/en-us/dotnet/api/system.icloneable" rel="noreferrer">ICloneable</a></strong>, which is <em>Shallow</em> and not <em>Type-Safe</em></li>\n<li><strong><a href="https://learn.microsoft.com/en-us/dotnet/api/system.object.memberwiseclone" rel="noreferrer">MemberwiseClone</a></strong>, which uses ICloneable</li>\n<li><strong><a href="https://www.codeproject.com/Articles/3441/Base-class-for-cloning-an-object-in-C" rel="noreferrer">Reflection</a></strong> by using <a href="https://learn.microsoft.com/en-us/dotnet/api/system.activator.createinstance" rel="noreferrer">Activator.CreateInstance</a> and <a href="https://github.com/Burtsev-Alexey/net-object-deep-copy/" rel="noreferrer">recursive MemberwiseClone</a></li>\n<li><strong><a href="https://learn.microsoft.com/en-us/dotnet/api/system.serializableattribute" rel="noreferrer">Serialization</a></strong>, as pointed by <a href="https://stackoverflow.com/a/78612/274502">johnc\'s preferred answer</a></li>\n<li><strong>Intermediate Language</strong>, which I got no idea <a href="https://whizzodev.blogspot.com/2008/03/object-cloning-using-il-in-c.html" rel="noreferrer">how works</a></li>\n<li><strong>Extension Methods</strong>, such as this <a href="https://circlesandcrossesblogarchive.blogspot.com/2008/01/extension-methods-for-copying-or.html" rel="noreferrer">custom clone framework by Havard Straden</a></li>\n<li><strong><a href="https://www.codeproject.com/Articles/1111658/Fast-Deep-Copy-of-Objects-by-Expression-Trees-Csha" rel="noreferrer">Expression Trees</a></strong></li>\n</ul>\n\n<p>The <a href="https://www.codeproject.com/Articles/1111658/Fast-Deep-Copy-of-Objects-by-Expression-Trees-Csha" rel="noreferrer">article Fast Deep Copy by Expression Trees</a>   has  also performance comparison of cloning by Serialization, Reflection and Expression Trees.</p>\n\n<h1>Why I choose <em>ICloneable</em> (i.e. manually)</h1>\n\n<p><a href="http://www.agiledeveloper.com/articles/cloning072002.htm" rel="noreferrer">Mr Venkat Subramaniam (redundant link here) explains in much detail why</a>.</p>\n\n<p>All his article circles around an example that tries to be applicable for most cases, using 3 objects: <em>Person</em>, <em>Brain</em> and <em>City</em>. We want to clone a person, which will have its own brain but the same city. You can either picture all problems any of the other methods above can bring or read the article.</p>\n\n<p>This is my slightly modified version of his conclusion:</p>\n\n<blockquote>\n  <p>Copying an object by specifying <code>New</code> followed by the class name often leads to code that is not extensible. Using clone, the application of prototype pattern, is a better way to achieve this. However, using clone as it is provided in C# (and Java) can be quite problematic as well. It is better to provide a protected (non-public) copy constructor and invoke that from the clone method. This gives us the ability to delegate the task of creating an object to an instance of a class itself, thus providing extensibility and also, safely creating the objects using the protected copy constructor.</p>\n</blockquote>\n\n<p>Hopefully this implementation can make things clear:</p>\n\n<pre><code>public class Person : ICloneable\n{\n    private final Brain brain; // brain is final since I do not want \n                // any transplant on it once created!\n    private int age;\n    public Person(Brain aBrain, int theAge)\n    {\n        brain = aBrain; \n        age = theAge;\n    }\n    protected Person(Person another)\n    {\n        Brain refBrain = null;\n        try\n        {\n            refBrain = (Brain) another.brain.clone();\n            // You can set the brain in the constructor\n        }\n        catch(CloneNotSupportedException e) {}\n        brain = refBrain;\n        age = another.age;\n    }\n    public String toString()\n    {\n        return "This is person with " + brain;\n        // Not meant to sound rude as it reads!\n    }\n    public Object clone()\n    {\n        return new Person(this);\n    }\n    …\n}\n</code></pre>\n\n<p>Now consider having a class derive from Person.</p>\n\n<pre><code>public class SkilledPerson extends Person\n{\n    private String theSkills;\n    public SkilledPerson(Brain aBrain, int theAge, String skills)\n    {\n        super(aBrain, theAge);\n        theSkills = skills;\n    }\n    protected SkilledPerson(SkilledPerson another)\n    {\n        super(another);\n        theSkills = another.theSkills;\n    }\n\n    public Object clone()\n    {\n        return new SkilledPerson(this);\n    }\n    public String toString()\n    {\n        return "SkilledPerson: " + super.toString();\n    }\n}\n</code></pre>\n\n<p>You may try running the following code:</p>\n\n<pre><code>public class User\n{\n    public static void play(Person p)\n    {\n        Person another = (Person) p.clone();\n        System.out.println(p);\n        System.out.println(another);\n    }\n    public static void main(String[] args)\n    {\n        Person sam = new Person(new Brain(), 1);\n        play(sam);\n        SkilledPerson bob = new SkilledPerson(new SmarterBrain(), 1, "Writer");\n        play(bob);\n    }\n}\n</code></pre>\n\n<p>The output produced will be:</p>\n\n<pre><code>This is person with Brain@1fcc69\nThis is person with Brain@253498\nSkilledPerson: This is person with SmarterBrain@1fef6f\nSkilledPerson: This is person with SmarterBrain@209f4e\n</code></pre>\n\n<p>Observe that, if we keep a count of the number of objects, the clone as implemented here will keep a correct count of the number of objects.</p>\n'}, {'answer_id': 12901265, 'author': 'Michael Cox', 'author_id': 372698, 'author_profile': 'https://Stackoverflow.com/users/372698', 'pm_score': 5, 'selected': False, 'text': '<p>If you\'re already using a 3rd party application like <a href="https://github.com/omuleanu/ValueInjecter" rel="noreferrer">ValueInjecter</a> or <a href="https://github.com/AutoMapper/AutoMapper" rel="noreferrer">Automapper</a>, you can do something like this:</p>\n\n<pre><code>MyObject oldObj; // The existing object to clone\n\nMyObject newObj = new MyObject();\nnewObj.InjectFrom(oldObj); // Using ValueInjecter syntax\n</code></pre>\n\n<p>Using this method you don\'t have to implement <code>ISerializable</code> or <code>ICloneable</code> on your objects. This is common with the MVC/MVVM pattern, so simple tools like this have been created.</p>\n\n<p>see <a href="https://github.com/omuleanu/ValueInjecter/blob/dae7956439cac8516979fe254a520a1942c5cdeb/Tests/Cloning.cs" rel="noreferrer">the ValueInjecter deep cloning sample on GitHub</a>.</p>\n'}, {'answer_id': 15788750, 'author': 'craastad', 'author_id': 1111732, 'author_profile': 'https://Stackoverflow.com/users/1111732', 'pm_score': 9, 'selected': False, 'text': '<p>I wanted a cloner for very simple objects of mostly primitives and lists.  If your object is out of the box JSON serializable then this method will do the trick.  This requires no modification or implementation of interfaces on the cloned class, just a JSON serializer like JSON.NET.</p>\n\n<pre><code>public static T Clone&lt;T&gt;(T source)\n{\n    var serialized = JsonConvert.SerializeObject(source);\n    return JsonConvert.DeserializeObject&lt;T&gt;(serialized);\n}\n</code></pre>\n\n<p>Also, you can use this extension method</p>\n\n<pre><code>public static class SystemExtension\n{\n    public static T Clone&lt;T&gt;(this T source)\n    {\n        var serialized = JsonConvert.SerializeObject(source);\n        return JsonConvert.DeserializeObject&lt;T&gt;(serialized);\n    }\n}\n</code></pre>\n'}, {'answer_id': 18123706, 'author': 'Ylli Prifti', 'author_id': 693312, 'author_profile': 'https://Stackoverflow.com/users/693312', 'pm_score': 1, 'selected': False, 'text': '<p>This will copy all readable and writable properties of an object to another.</p>\n\n<pre><code> public class PropertyCopy&lt;TSource, TTarget&gt; \n                        where TSource: class, new()\n                        where TTarget: class, new()\n        {\n            public static TTarget Copy(TSource src, TTarget trg, params string[] properties)\n            {\n                if (src==null) return trg;\n                if (trg == null) trg = new TTarget();\n                var fulllist = src.GetType().GetProperties().Where(c =&gt; c.CanWrite &amp;&amp; c.CanRead).ToList();\n                if (properties != null &amp;&amp; properties.Count() &gt; 0)\n                    fulllist = fulllist.Where(c =&gt; properties.Contains(c.Name)).ToList();\n                if (fulllist == null || fulllist.Count() == 0) return trg;\n\n                fulllist.ForEach(c =&gt;\n                    {\n                        c.SetValue(trg, c.GetValue(src));\n                    });\n\n                return trg;\n            }\n        }\n</code></pre>\n\n<p>and this is how you use it: </p>\n\n<pre><code> var cloned = Utils.PropertyCopy&lt;TKTicket, TKTicket&gt;.Copy(_tmp, dbsave,\n                                                            "Creation",\n                                                            "Description",\n                                                            "IdTicketStatus",\n                                                            "IdUserCreated",\n                                                            "IdUserInCharge",\n                                                            "IdUserRequested",\n                                                            "IsUniqueTicketGenerated",\n                                                            "LastEdit",\n                                                            "Subject",\n                                                            "UniqeTicketRequestId",\n                                                            "Visibility");\n</code></pre>\n\n<p>or to copy everything: </p>\n\n<pre><code>var cloned = Utils.PropertyCopy&lt;TKTicket, TKTicket&gt;.Copy(_tmp, dbsave);\n</code></pre>\n'}, {'answer_id': 20767567, 'author': 'MarcinJuraszek', 'author_id': 1163867, 'author_profile': 'https://Stackoverflow.com/users/1163867', 'pm_score': 5, 'selected': False, 'text': '<p>I\'ve just created <strong><a href="https://github.com/MarcinJuraszek/CloneExtensions"><code>CloneExtensions</code> library</a></strong> project. It performs fast, deep clone using simple assignment operations generated by Expression Tree runtime code compilation.</p>\n\n<p><strong>How to use it?</strong></p>\n\n<p>Instead of writing your own <code>Clone</code> or <code>Copy</code> methods with a tone of assignments between fields and properties make the program do it for yourself, using Expression Tree. <code>GetClone&lt;T&gt;()</code> method marked as extension method allows you to simply call it on your instance:</p>\n\n<pre><code>var newInstance = source.GetClone();\n</code></pre>\n\n<p>You can choose what should be copied from <code>source</code> to <code>newInstance</code> using <code>CloningFlags</code> enum:</p>\n\n<pre><code>var newInstance \n    = source.GetClone(CloningFlags.Properties | CloningFlags.CollectionItems);\n</code></pre>\n\n<p><strong>What can be cloned?</strong></p>\n\n<ul>\n<li>Primitive (int, uint, byte, double, char, etc.), known immutable\ntypes (DateTime, TimeSpan, String) and delegates (including\nAction, Func, etc)</li>\n<li>Nullable</li>\n<li>T[] arrays</li>\n<li>Custom classes and structs, including generic classes and structs.</li>\n</ul>\n\n<p>Following class/struct members are cloned internally:</p>\n\n<ul>\n<li>Values of public, not readonly fields</li>\n<li>Values of public properties with both get and set accessors</li>\n<li>Collection items for types implementing ICollection</li>\n</ul>\n\n<p><strong>How fast it is?</strong></p>\n\n<p>The solution is faster then reflection, because members information has to be gathered only once, before <code>GetClone&lt;T&gt;</code> is used for the first time for given type <code>T</code>.</p>\n\n<p>It\'s also faster than serialization-based solution when you clone more then couple instances of the same type <code>T</code>.</p>\n\n<p><strong>and more...</strong></p>\n\n<p>Read more about generated expressions on <a href="https://github.com/MarcinJuraszek/CloneExtensions/blob/master/EXPRESSION_TREES.md">documentation</a>.</p>\n\n<p>Sample expression debug listing for <code>List&lt;int&gt;</code>:</p>\n\n<pre><code>.Lambda #Lambda1&lt;System.Func`4[System.Collections.Generic.List`1[System.Int32],CloneExtensions.CloningFlags,System.Collections.Generic.IDictionary`2[System.Type,System.Func`2[System.Object,System.Object]],System.Collections.Generic.List`1[System.Int32]]&gt;(\n    System.Collections.Generic.List`1[System.Int32] $source,\n    CloneExtensions.CloningFlags $flags,\n    System.Collections.Generic.IDictionary`2[System.Type,System.Func`2[System.Object,System.Object]] $initializers) {\n    .Block(System.Collections.Generic.List`1[System.Int32] $target) {\n        .If ($source == null) {\n            .Return #Label1 { null }\n        } .Else {\n            .Default(System.Void)\n        };\n        .If (\n            .Call $initializers.ContainsKey(.Constant&lt;System.Type&gt;(System.Collections.Generic.List`1[System.Int32]))\n        ) {\n            $target = (System.Collections.Generic.List`1[System.Int32]).Call ($initializers.Item[.Constant&lt;System.Type&gt;(System.Collections.Generic.List`1[System.Int32])]\n            ).Invoke((System.Object)$source)\n        } .Else {\n            $target = .New System.Collections.Generic.List`1[System.Int32]()\n        };\n        .If (\n            ((System.Byte)$flags &amp; (System.Byte).Constant&lt;CloneExtensions.CloningFlags&gt;(Fields)) == (System.Byte).Constant&lt;CloneExtensions.CloningFlags&gt;(Fields)\n        ) {\n            .Default(System.Void)\n        } .Else {\n            .Default(System.Void)\n        };\n        .If (\n            ((System.Byte)$flags &amp; (System.Byte).Constant&lt;CloneExtensions.CloningFlags&gt;(Properties)) == (System.Byte).Constant&lt;CloneExtensions.CloningFlags&gt;(Properties)\n        ) {\n            .Block() {\n                $target.Capacity = .Call CloneExtensions.CloneFactory.GetClone(\n                    $source.Capacity,\n                    $flags,\n                    $initializers)\n            }\n        } .Else {\n            .Default(System.Void)\n        };\n        .If (\n            ((System.Byte)$flags &amp; (System.Byte).Constant&lt;CloneExtensions.CloningFlags&gt;(CollectionItems)) == (System.Byte).Constant&lt;CloneExtensions.CloningFlags&gt;(CollectionItems)\n        ) {\n            .Block(\n                System.Collections.Generic.IEnumerator`1[System.Int32] $var1,\n                System.Collections.Generic.ICollection`1[System.Int32] $var2) {\n                $var1 = (System.Collections.Generic.IEnumerator`1[System.Int32]).Call $source.GetEnumerator();\n                $var2 = (System.Collections.Generic.ICollection`1[System.Int32])$target;\n                .Loop  {\n                    .If (.Call $var1.MoveNext() != False) {\n                        .Call $var2.Add(.Call CloneExtensions.CloneFactory.GetClone(\n                                $var1.Current,\n                                $flags,\n\n\n                         $initializers))\n                } .Else {\n                    .Break #Label2 { }\n                }\n            }\n            .LabelTarget #Label2:\n        }\n    } .Else {\n        .Default(System.Void)\n    };\n    .Label\n        $target\n    .LabelTarget #Label1:\n}\n</code></pre>\n\n<p>}</p>\n\n<p>what has the same meaning like following c# code:</p>\n\n<pre><code>(source, flags, initializers) =&gt;\n{\n    if(source == null)\n        return null;\n\n    if(initializers.ContainsKey(typeof(List&lt;int&gt;))\n        target = (List&lt;int&gt;)initializers[typeof(List&lt;int&gt;)].Invoke((object)source);\n    else\n        target = new List&lt;int&gt;();\n\n    if((flags &amp; CloningFlags.Properties) == CloningFlags.Properties)\n    {\n        target.Capacity = target.Capacity.GetClone(flags, initializers);\n    }\n\n    if((flags &amp; CloningFlags.CollectionItems) == CloningFlags.CollectionItems)\n    {\n        var targetCollection = (ICollection&lt;int&gt;)target;\n        foreach(var item in (ICollection&lt;int&gt;)source)\n        {\n            targetCollection.Add(item.Clone(flags, initializers));\n        }\n    }\n\n    return target;\n}\n</code></pre>\n\n<p>Isn\'t it quite like how you\'d write your own <code>Clone</code> method for <code>List&lt;int&gt;</code>?</p>\n'}, {'answer_id': 23017515, 'author': 'Jeroen Ritmeijer', 'author_id': 79448, 'author_profile': 'https://Stackoverflow.com/users/79448', 'pm_score': 2, 'selected': False, 'text': '<p>I have created a version of the accepted answer that works with both \'[Serializable]\' and \'[DataContract]\'. It has been a while since I wrote it, but if I remember correctly [DataContract] needed a different serializer.</p>\n\n<p>Requires <em>System, System.IO, System.Runtime.Serialization, System.Runtime.Serialization.Formatters.Binary, System.Xml</em>;</p>\n\n<pre><code>public static class ObjectCopier\n{\n\n    /// &lt;summary&gt;\n    /// Perform a deep Copy of an object that is marked with \'[Serializable]\' or \'[DataContract]\'\n    /// &lt;/summary&gt;\n    /// &lt;typeparam name="T"&gt;The type of object being copied.&lt;/typeparam&gt;\n    /// &lt;param name="source"&gt;The object instance to copy.&lt;/param&gt;\n    /// &lt;returns&gt;The copied object.&lt;/returns&gt;\n    public static T Clone&lt;T&gt;(T source)\n    {\n        if (typeof(T).IsSerializable == true)\n        {\n            return CloneUsingSerializable&lt;T&gt;(source);\n        }\n\n        if (IsDataContract(typeof(T)) == true)\n        {\n            return CloneUsingDataContracts&lt;T&gt;(source);\n        }\n\n        throw new ArgumentException("The type must be Serializable or use DataContracts.", "source");\n    }\n\n\n    /// &lt;summary&gt;\n    /// Perform a deep Copy of an object that is marked with \'[Serializable]\'\n    /// &lt;/summary&gt;\n    /// &lt;remarks&gt;\n    /// Found on http://stackoverflow.com/questions/78536/cloning-objects-in-c-sharp\n    /// Uses code found on CodeProject, which allows free use in third party apps\n    /// - http://www.codeproject.com/KB/tips/SerializedObjectCloner.aspx\n    /// &lt;/remarks&gt;\n    /// &lt;typeparam name="T"&gt;The type of object being copied.&lt;/typeparam&gt;\n    /// &lt;param name="source"&gt;The object instance to copy.&lt;/param&gt;\n    /// &lt;returns&gt;The copied object.&lt;/returns&gt;\n    public static T CloneUsingSerializable&lt;T&gt;(T source)\n    {\n        if (!typeof(T).IsSerializable)\n        {\n            throw new ArgumentException("The type must be serializable.", "source");\n        }\n\n        // Don\'t serialize a null object, simply return the default for that object\n        if (Object.ReferenceEquals(source, null))\n        {\n            return default(T);\n        }\n\n        IFormatter formatter = new BinaryFormatter();\n        Stream stream = new MemoryStream();\n        using (stream)\n        {\n            formatter.Serialize(stream, source);\n            stream.Seek(0, SeekOrigin.Begin);\n            return (T)formatter.Deserialize(stream);\n        }\n    }\n\n\n    /// &lt;summary&gt;\n    /// Perform a deep Copy of an object that is marked with \'[DataContract]\'\n    /// &lt;/summary&gt;\n    /// &lt;typeparam name="T"&gt;The type of object being copied.&lt;/typeparam&gt;\n    /// &lt;param name="source"&gt;The object instance to copy.&lt;/param&gt;\n    /// &lt;returns&gt;The copied object.&lt;/returns&gt;\n    public static T CloneUsingDataContracts&lt;T&gt;(T source)\n    {\n        if (IsDataContract(typeof(T)) == false)\n        {\n            throw new ArgumentException("The type must be a data contract.", "source");\n        }\n\n        // ** Don\'t serialize a null object, simply return the default for that object\n        if (Object.ReferenceEquals(source, null))\n        {\n            return default(T);\n        }\n\n        DataContractSerializer dcs = new DataContractSerializer(typeof(T));\n        using(Stream stream = new MemoryStream())\n        {\n            using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateBinaryWriter(stream))\n            {\n                dcs.WriteObject(writer, source);\n                writer.Flush();\n                stream.Seek(0, SeekOrigin.Begin);\n                using (XmlDictionaryReader reader = XmlDictionaryReader.CreateBinaryReader(stream, XmlDictionaryReaderQuotas.Max))\n                {\n                    return (T)dcs.ReadObject(reader);\n                }\n            }\n        }\n    }\n\n\n    /// &lt;summary&gt;\n    /// Helper function to check if a class is a [DataContract]\n    /// &lt;/summary&gt;\n    /// &lt;param name="type"&gt;The type of the object to check.&lt;/param&gt;\n    /// &lt;returns&gt;Boolean flag indicating if the class is a DataContract (true) or not (false) &lt;/returns&gt;\n    public static bool IsDataContract(Type type)\n    {\n        object[] attributes = type.GetCustomAttributes(typeof(DataContractAttribute), false);\n        return attributes.Length == 1;\n    }\n\n} \n</code></pre>\n'}, {'answer_id': 23042982, 'author': 'will_m', 'author_id': 3528734, 'author_profile': 'https://Stackoverflow.com/users/3528734', 'pm_score': 1, 'selected': False, 'text': '<p>how about just recasting inside a method \nthat should invoke basically a automatic copy constructor</p>\n\n<pre><code>T t = new T();\nT t2 = (T)t;  //eh something like that\n\n        List&lt;myclass&gt; cloneum;\n        public void SomeFuncB(ref List&lt;myclass&gt; _mylist)\n        {\n            cloneum = new List&lt;myclass&gt;();\n            cloneum = (List &lt; myclass &gt;) _mylist;\n            cloneum.Add(new myclass(3));\n            _mylist = new List&lt;myclass&gt;();\n        }\n</code></pre>\n\n<p>seems to work to me</p>\n'}, {'answer_id': 23289451, 'author': 'Chtioui Malek', 'author_id': 1254684, 'author_profile': 'https://Stackoverflow.com/users/1254684', 'pm_score': 2, 'selected': False, 'text': '<p>To clone your class object you can use the Object.MemberwiseClone method,</p>\n\n<p>just add this function to your class :</p>\n\n<pre><code>public class yourClass\n{\n    // ...\n    // ...\n\n    public yourClass DeepCopy()\n    {\n        yourClass othercopy = (yourClass)this.MemberwiseClone();\n        return othercopy;\n    }\n}\n</code></pre>\n\n<p>then to perform a deep independant copy, just call the DeepCopy method :</p>\n\n<pre><code>yourClass newLine = oldLine.DeepCopy();\n</code></pre>\n\n<p>hope this helps.</p>\n'}, {'answer_id': 28540467, 'author': 'Michael Sander', 'author_id': 564508, 'author_profile': 'https://Stackoverflow.com/users/564508', 'pm_score': 4, 'selected': False, 'text': '<p>EDIT: project is discontinued</p>\n\n<p>If you want true cloning to unknown types you can take a look at\n<a href="http://fastclone.codeplex.com/" rel="nofollow noreferrer">fastclone</a>.</p>\n\n<p>That\'s expression based cloning working about 10 times faster than binary serialization and maintaining complete object graph integrity.</p>\n\n<p>That means: if you refer multiple times to the same object in your hierachy, the clone will also have a single instance beeing referenced.</p>\n\n<p>There is no need for interfaces, attributes or any other modification to the objects being cloned.</p>\n'}, {'answer_id': 28900160, 'author': 'LuckyLikey', 'author_id': 4099159, 'author_profile': 'https://Stackoverflow.com/users/4099159', 'pm_score': 3, 'selected': False, 'text': '<p>I like Copyconstructors like that:</p>\n\n<pre><code>    public AnyObject(AnyObject anyObject)\n    {\n        foreach (var property in typeof(AnyObject).GetProperties())\n        {\n            property.SetValue(this, property.GetValue(anyObject));\n        }\n        foreach (var field in typeof(AnyObject).GetFields())\n        {\n            field.SetValue(this, field.GetValue(anyObject));\n        }\n    }\n</code></pre>\n\n<p>If you have more things to copy add them</p>\n'}, {'answer_id': 29749841, 'author': 'LuckyLikey', 'author_id': 4099159, 'author_profile': 'https://Stackoverflow.com/users/4099159', 'pm_score': 2, 'selected': False, 'text': "<p>If your Object Tree is Serializeable you could also use something like this</p>\n\n<pre><code>static public MyClass Clone(MyClass myClass)\n{\n    MyClass clone;\n    XmlSerializer ser = new XmlSerializer(typeof(MyClass), _xmlAttributeOverrides);\n    using (var ms = new MemoryStream())\n    {\n        ser.Serialize(ms, myClass);\n        ms.Position = 0;\n        clone = (MyClass)ser.Deserialize(ms);\n    }\n    return clone;\n}\n</code></pre>\n\n<p>be informed that this Solution is pretty easy but it's not as performant as other solutions may be.</p>\n\n<p>And be sure that if the Class grows, there will still be only those fields cloned, which also get serialized.</p>\n"}, {'answer_id': 29856064, 'author': 'TarmoPikaro', 'author_id': 2338477, 'author_profile': 'https://Stackoverflow.com/users/2338477', 'pm_score': 2, 'selected': False, 'text': '<p>It\'s unbelievable how much effort you can spend with IClonable interface - especially if you have heavy class hierarchies. Also MemberwiseClone works somehow oddly - it does not exactly clone even normal List type kind of structures.</p>\n\n<p>And of course most interesting dilemma for serialization is to serialize back references - e.g. class hierarchies where you have child-parent relationships.\nI doubt that binary serializer will be able to help you in this case. (It will end up with recursive loops + stack overflow).</p>\n\n<p>I somehow liked solution proposed here: <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>\n\n<p>however - it did not support Lists, added that support, also took into account re-parenting. \nFor parenting only rule which I have made that field or property should be named "parent", then it will be ignored by DeepClone. You might want to decide your own rules for back-references - for tree hierarchies it might be "left/right", etc...</p>\n\n<p>Here is whole code snippet including test code: </p>\n\n<pre><code>using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Reflection;\nusing System.Text;\n\nnamespace TestDeepClone\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            A a = new A();\n            a.name = "main_A";\n            a.b_list.Add(new B(a) { name = "b1" });\n            a.b_list.Add(new B(a) { name = "b2" });\n\n            A a2 = (A)a.DeepClone();\n            a2.name = "second_A";\n\n            // Perform re-parenting manually after deep copy.\n            foreach( var b in a2.b_list )\n                b.parent = a2;\n\n\n            Debug.WriteLine("ok");\n\n        }\n    }\n\n    public class A\n    {\n        public String name = "one";\n        public List&lt;String&gt; list = new List&lt;string&gt;();\n        public List&lt;String&gt; null_list;\n        public List&lt;B&gt; b_list = new List&lt;B&gt;();\n        private int private_pleaseCopyMeAsWell = 5;\n\n        public override string ToString()\n        {\n            return "A(" + name + ")";\n        }\n    }\n\n    public class B\n    {\n        public B() { }\n        public B(A _parent) { parent = _parent; }\n        public A parent;\n        public String name = "two";\n    }\n\n\n    public static class ReflectionEx\n    {\n        public static Type GetUnderlyingType(this MemberInfo member)\n        {\n            Type type;\n            switch (member.MemberType)\n            {\n                case MemberTypes.Field:\n                    type = ((FieldInfo)member).FieldType;\n                    break;\n                case MemberTypes.Property:\n                    type = ((PropertyInfo)member).PropertyType;\n                    break;\n                case MemberTypes.Event:\n                    type = ((EventInfo)member).EventHandlerType;\n                    break;\n                default:\n                    throw new ArgumentException("member must be if type FieldInfo, PropertyInfo or EventInfo", "member");\n            }\n            return Nullable.GetUnderlyingType(type) ?? type;\n        }\n\n        /// &lt;summary&gt;\n        /// Gets fields and properties into one array.\n        /// Order of properties / fields will be preserved in order of appearance in class / struct. (MetadataToken is used for sorting such cases)\n        /// &lt;/summary&gt;\n        /// &lt;param name="type"&gt;Type from which to get&lt;/param&gt;\n        /// &lt;returns&gt;array of fields and properties&lt;/returns&gt;\n        public static MemberInfo[] GetFieldsAndProperties(this Type type)\n        {\n            List&lt;MemberInfo&gt; fps = new List&lt;MemberInfo&gt;();\n            fps.AddRange(type.GetFields());\n            fps.AddRange(type.GetProperties());\n            fps = fps.OrderBy(x =&gt; x.MetadataToken).ToList();\n            return fps.ToArray();\n        }\n\n        public static object GetValue(this MemberInfo member, object target)\n        {\n            if (member is PropertyInfo)\n            {\n                return (member as PropertyInfo).GetValue(target, null);\n            }\n            else if (member is FieldInfo)\n            {\n                return (member as FieldInfo).GetValue(target);\n            }\n            else\n            {\n                throw new Exception("member must be either PropertyInfo or FieldInfo");\n            }\n        }\n\n        public static void SetValue(this MemberInfo member, object target, object value)\n        {\n            if (member is PropertyInfo)\n            {\n                (member as PropertyInfo).SetValue(target, value, null);\n            }\n            else if (member is FieldInfo)\n            {\n                (member as FieldInfo).SetValue(target, value);\n            }\n            else\n            {\n                throw new Exception("destinationMember must be either PropertyInfo or FieldInfo");\n            }\n        }\n\n        /// &lt;summary&gt;\n        /// Deep clones specific object.\n        /// Analogue can be found here: https://stackoverflow.com/questions/129389/how-do-you-do-a-deep-copy-an-object-in-net-c-specifically\n        /// This is now improved version (list support added)\n        /// &lt;/summary&gt;\n        /// &lt;param name="obj"&gt;object to be cloned&lt;/param&gt;\n        /// &lt;returns&gt;full copy of object.&lt;/returns&gt;\n        public static object DeepClone(this object obj)\n        {\n            if (obj == null)\n                return null;\n\n            Type type = obj.GetType();\n\n            if (obj is IList)\n            {\n                IList list = ((IList)obj);\n                IList newlist = (IList)Activator.CreateInstance(obj.GetType(), list.Count);\n\n                foreach (object elem in list)\n                    newlist.Add(DeepClone(elem));\n\n                return newlist;\n            } //if\n\n            if (type.IsValueType || type == typeof(string))\n            {\n                return obj;\n            }\n            else if (type.IsArray)\n            {\n                Type elementType = Type.GetType(type.FullName.Replace("[]", string.Empty));\n                var array = obj as Array;\n                Array copied = Array.CreateInstance(elementType, array.Length);\n\n                for (int i = 0; i &lt; array.Length; i++)\n                    copied.SetValue(DeepClone(array.GetValue(i)), i);\n\n                return Convert.ChangeType(copied, obj.GetType());\n            }\n            else if (type.IsClass)\n            {\n                object toret = Activator.CreateInstance(obj.GetType());\n\n                MemberInfo[] fields = type.GetFieldsAndProperties();\n                foreach (MemberInfo field in fields)\n                {\n                    // Don\'t clone parent back-reference classes. (Using special kind of naming \'parent\' \n                    // to indicate child\'s parent class.\n                    if (field.Name == "parent")\n                    {\n                        continue;\n                    }\n\n                    object fieldValue = field.GetValue(obj);\n\n                    if (fieldValue == null)\n                        continue;\n\n                    field.SetValue(toret, DeepClone(fieldValue));\n                }\n\n                return toret;\n            }\n            else\n            {\n                // Don\'t know that type, don\'t know how to clone it.\n                if (Debugger.IsAttached)\n                    Debugger.Break();\n\n                return null;\n            }\n        } //DeepClone\n    }\n\n}\n</code></pre>\n'}, {'answer_id': 31223335, 'author': 'Contango', 'author_id': 107409, 'author_profile': 'https://Stackoverflow.com/users/107409', 'pm_score': 4, 'selected': False, 'text': '<h3>Q. Why would I choose this answer?</h3>\n<ul>\n<li>Choose this answer if you want the fastest speed .NET is capable of.</li>\n<li>Ignore this answer if you want a really, really easy method of cloning.</li>\n</ul>\n<p>In other words, <a href="http://c2.com/cgi/wiki?PrematureOptimization" rel="noreferrer">go with another answer unless you have a performance bottleneck that needs fixing, and you can prove it with a profiler</a>.</p>\n<h3>10x faster than other methods</h3>\n<p>The following method of performing a deep clone is:</p>\n<ul>\n<li>10x faster than anything that involves serialization/deserialization;</li>\n<li>Pretty darn close to the theoretical maximum speed .NET is capable of.</li>\n</ul>\n<h3>And the method ...</h3>\n<p>For ultimate speed, you can use <strong>Nested MemberwiseClone to do a deep copy</strong>. Its almost the same speed as copying a value struct, and is much faster than (a) reflection or (b) serialization (as described in other answers on this page).</p>\n<p>Note that <strong>if</strong> you use <strong>Nested MemberwiseClone for a deep copy</strong>, you have to manually implement a ShallowCopy for each nested level in the class, and a DeepCopy which calls all said ShallowCopy methods to create a complete clone. This is simple: only a few lines in total, see the demo code below.</p>\n<p>Here is the output of the code showing the relative performance difference for 100,000 clones:</p>\n<ul>\n<li>1.08 seconds for Nested MemberwiseClone on nested structs</li>\n<li>4.77 seconds for Nested MemberwiseClone on nested classes</li>\n<li>39.93 seconds for Serialization/Deserialization</li>\n</ul>\n<p>Using Nested MemberwiseClone on a class almost as fast as copying a struct, and copying a struct is pretty darn close to the theoretical maximum speed .NET is capable of.</p>\n<pre><code>Demo 1 of shallow and deep copy, using classes and MemberwiseClone:\n  Create Bob\n    Bob.Age=30, Bob.Purchase.Description=Lamborghini\n  Clone Bob &gt;&gt; BobsSon\n  Adjust BobsSon details\n    BobsSon.Age=2, BobsSon.Purchase.Description=Toy car\n  Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:\n    Bob.Age=30, Bob.Purchase.Description=Lamborghini\n  Elapsed time: 00:00:04.7795670,30000000\n\nDemo 2 of shallow and deep copy, using structs and value copying:\n  Create Bob\n    Bob.Age=30, Bob.Purchase.Description=Lamborghini\n  Clone Bob &gt;&gt; BobsSon\n  Adjust BobsSon details:\n    BobsSon.Age=2, BobsSon.Purchase.Description=Toy car\n  Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:\n    Bob.Age=30, Bob.Purchase.Description=Lamborghini\n  Elapsed time: 00:00:01.0875454,30000000\n\nDemo 3 of deep copy, using class and serialize/deserialize:\n  Elapsed time: 00:00:39.9339425,30000000\n</code></pre>\n<p>To understand how to do a deep copy using MemberwiseCopy, here is the demo project that was used to generate the times above:</p>\n<pre><code>// Nested MemberwiseClone example. \n// Added to demo how to deep copy a reference class.\n[Serializable] // Not required if using MemberwiseClone, only used for speed comparison using serialization.\npublic class Person\n{\n    public Person(int age, string description)\n    {\n        this.Age = age;\n        this.Purchase.Description = description;\n    }\n    [Serializable] // Not required if using MemberwiseClone\n    public class PurchaseType\n    {\n        public string Description;\n        public PurchaseType ShallowCopy()\n        {\n            return (PurchaseType)this.MemberwiseClone();\n        }\n    }\n    public PurchaseType Purchase = new PurchaseType();\n    public int Age;\n    // Add this if using nested MemberwiseClone.\n    // This is a class, which is a reference type, so cloning is more difficult.\n    public Person ShallowCopy()\n    {\n        return (Person)this.MemberwiseClone();\n    }\n    // Add this if using nested MemberwiseClone.\n    // This is a class, which is a reference type, so cloning is more difficult.\n    public Person DeepCopy()\n    {\n            // Clone the root ...\n        Person other = (Person) this.MemberwiseClone();\n            // ... then clone the nested class.\n        other.Purchase = this.Purchase.ShallowCopy();\n        return other;\n    }\n}\n// Added to demo how to copy a value struct (this is easy - a deep copy happens by default)\npublic struct PersonStruct\n{\n    public PersonStruct(int age, string description)\n    {\n        this.Age = age;\n        this.Purchase.Description = description;\n    }\n    public struct PurchaseType\n    {\n        public string Description;\n    }\n    public PurchaseType Purchase;\n    public int Age;\n    // This is a struct, which is a value type, so everything is a clone by default.\n    public PersonStruct ShallowCopy()\n    {\n        return (PersonStruct)this;\n    }\n    // This is a struct, which is a value type, so everything is a clone by default.\n    public PersonStruct DeepCopy()\n    {\n        return (PersonStruct)this;\n    }\n}\n// Added only for a speed comparison.\npublic class MyDeepCopy\n{\n    public static T DeepCopy&lt;T&gt;(T obj)\n    {\n        object result = null;\n        using (var ms = new MemoryStream())\n        {\n            var formatter = new BinaryFormatter();\n            formatter.Serialize(ms, obj);\n            ms.Position = 0;\n            result = (T)formatter.Deserialize(ms);\n            ms.Close();\n        }\n        return (T)result;\n    }\n}\n</code></pre>\n<p>Then, call the demo from main:</p>\n<pre><code>void MyMain(string[] args)\n{\n    {\n        Console.Write(&quot;Demo 1 of shallow and deep copy, using classes and MemberwiseCopy:\\n&quot;);\n        var Bob = new Person(30, &quot;Lamborghini&quot;);\n        Console.Write(&quot;  Create Bob\\n&quot;);\n        Console.Write(&quot;    Bob.Age={0}, Bob.Purchase.Description={1}\\n&quot;, Bob.Age, Bob.Purchase.Description);\n        Console.Write(&quot;  Clone Bob &gt;&gt; BobsSon\\n&quot;);\n        var BobsSon = Bob.DeepCopy();\n        Console.Write(&quot;  Adjust BobsSon details\\n&quot;);\n        BobsSon.Age = 2;\n        BobsSon.Purchase.Description = &quot;Toy car&quot;;\n        Console.Write(&quot;    BobsSon.Age={0}, BobsSon.Purchase.Description={1}\\n&quot;, BobsSon.Age, BobsSon.Purchase.Description);\n        Console.Write(&quot;  Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:\\n&quot;);\n        Console.Write(&quot;    Bob.Age={0}, Bob.Purchase.Description={1}\\n&quot;, Bob.Age, Bob.Purchase.Description);\n        Debug.Assert(Bob.Age == 30);\n        Debug.Assert(Bob.Purchase.Description == &quot;Lamborghini&quot;);\n        var sw = new Stopwatch();\n        sw.Start();\n        int total = 0;\n        for (int i = 0; i &lt; 100000; i++)\n        {\n            var n = Bob.DeepCopy();\n            total += n.Age;\n        }\n        Console.Write(&quot;  Elapsed time: {0},{1}\\n\\n&quot;, sw.Elapsed, total);\n    }\n    {               \n        Console.Write(&quot;Demo 2 of shallow and deep copy, using structs:\\n&quot;);\n        var Bob = new PersonStruct(30, &quot;Lamborghini&quot;);\n        Console.Write(&quot;  Create Bob\\n&quot;);\n        Console.Write(&quot;    Bob.Age={0}, Bob.Purchase.Description={1}\\n&quot;, Bob.Age, Bob.Purchase.Description);\n        Console.Write(&quot;  Clone Bob &gt;&gt; BobsSon\\n&quot;);\n        var BobsSon = Bob.DeepCopy();\n        Console.Write(&quot;  Adjust BobsSon details:\\n&quot;);\n        BobsSon.Age = 2;\n        BobsSon.Purchase.Description = &quot;Toy car&quot;;\n        Console.Write(&quot;    BobsSon.Age={0}, BobsSon.Purchase.Description={1}\\n&quot;, BobsSon.Age, BobsSon.Purchase.Description);\n        Console.Write(&quot;  Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:\\n&quot;);\n        Console.Write(&quot;    Bob.Age={0}, Bob.Purchase.Description={1}\\n&quot;, Bob.Age, Bob.Purchase.Description);                \n        Debug.Assert(Bob.Age == 30);\n        Debug.Assert(Bob.Purchase.Description == &quot;Lamborghini&quot;);\n        var sw = new Stopwatch();\n        sw.Start();\n        int total = 0;\n        for (int i = 0; i &lt; 100000; i++)\n        {\n            var n = Bob.DeepCopy();\n            total += n.Age;\n        }\n        Console.Write(&quot;  Elapsed time: {0},{1}\\n\\n&quot;, sw.Elapsed, total);\n    }\n    {\n        Console.Write(&quot;Demo 3 of deep copy, using class and serialize/deserialize:\\n&quot;);\n        int total = 0;\n        var sw = new Stopwatch();\n        sw.Start();\n        var Bob = new Person(30, &quot;Lamborghini&quot;);\n        for (int i = 0; i &lt; 100000; i++)\n        {\n            var BobsSon = MyDeepCopy.DeepCopy&lt;Person&gt;(Bob);\n            total += BobsSon.Age;\n        }\n        Console.Write(&quot;  Elapsed time: {0},{1}\\n&quot;, sw.Elapsed, total);\n    }\n    Console.ReadKey();\n}\n</code></pre>\n<p>Again, note that <strong>if</strong> you use <strong>Nested MemberwiseClone for a deep copy</strong>, you have to manually implement a ShallowCopy for each nested level in the class, and a DeepCopy which calls all said ShallowCopy methods to create a complete clone. This is simple: only a few lines in total, see the demo code above.</p>\n<h3>Value types vs. References Types</h3>\n<p>Note that when it comes to cloning an object, there is is a big difference between a &quot;<strong>struct</strong>&quot; and a &quot;<strong>class</strong>&quot;:</p>\n<ul>\n<li>If you have a &quot;<strong>struct</strong>&quot;, it\'s a <strong>value type</strong> so you can just copy it, and the contents will be cloned (but it will only make a shallow clone unless you use the techniques in this post).</li>\n<li>If you have a &quot;<strong>class</strong>&quot;, it\'s a <strong>reference type</strong>, so if you copy it, all you are doing is copying the pointer to it. To create a true clone, you have to be more creative, and use <a href="https://msdn.microsoft.com/en-us/library/system.object.memberwiseclone(v=vs.110).aspx" rel="noreferrer">differences between value types and references types</a> which creates another copy of the original object in memory.</li>\n</ul>\n<p>See <a href="https://msdn.microsoft.com/en-us/library/system.object.memberwiseclone(v=vs.110).aspx" rel="noreferrer">differences between value types and references types</a>.</p>\n<h3>Checksums to aid in debugging</h3>\n<ul>\n<li>Cloning objects incorrectly can lead to very difficult-to-pin-down bugs. In production code, I tend to implement a checksum to double check that the object has been cloned properly, and hasn\'t been corrupted by another reference to it. This checksum can be switched off in Release mode.</li>\n<li>I find this method quite useful: often, you only want to clone parts of the object, not the entire thing.</li>\n</ul>\n<h3>Really useful for decoupling many threads from many other threads</h3>\n<p>One excellent use case for this code is feeding clones of a nested class or struct into a queue, to implement the producer / consumer pattern.</p>\n<ul>\n<li>We can have one  (or more) threads modifying a class that they own, then pushing a complete copy of this class into a <code>ConcurrentQueue</code>.</li>\n<li>We then have one (or more) threads pulling copies of these classes out and dealing with them.</li>\n</ul>\n<p>This works extremely well in practice, and allows us to decouple many threads (the producers) from one or more threads (the consumers).</p>\n<p>And this method is blindingly fast too: if we use nested structs, it\'s 35x faster than serializing/deserializing nested classes, and allows us to take advantage of all of the threads available on the machine.</p>\n<h1>Update</h1>\n<p>Apparently, ExpressMapper is as fast, if not faster, than hand coding such as above. I might have to see how they compare with a profiler.</p>\n'}, {'answer_id': 32155648, 'author': 'KeyNone', 'author_id': 1807643, 'author_profile': 'https://Stackoverflow.com/users/1807643', 'pm_score': 1, 'selected': False, 'text': '<p>When using Marc Gravells protobuf-net as your serializer the accepted answer needs some slight modifications, as the object to copy won\'t be attributed with <code>[Serializable]</code> and, therefore, isn\'t serializable and the Clone-method will throw an exception.<br>\nI modified it to work with protobuf-net:</p>\n\n<pre><code>public static T Clone&lt;T&gt;(this T source)\n{\n    if(Attribute.GetCustomAttribute(typeof(T), typeof(ProtoBuf.ProtoContractAttribute))\n           == null)\n    {\n        throw new ArgumentException("Type has no ProtoContract!", "source");\n    }\n\n    if(Object.ReferenceEquals(source, null))\n    {\n        return default(T);\n    }\n\n    IFormatter formatter = ProtoBuf.Serializer.CreateFormatter&lt;T&gt;();\n    using (Stream stream = new MemoryStream())\n    {\n        formatter.Serialize(stream, source);\n        stream.Seek(0, SeekOrigin.Begin);\n        return (T)formatter.Deserialize(stream);\n    }\n}\n</code></pre>\n\n<p>This checks for the presence of a <code>[ProtoContract]</code> attribute and uses protobufs own formatter to serialize the object.</p>\n'}, {'answer_id': 34368738, 'author': 'Roma Borodov', 'author_id': 4711853, 'author_profile': 'https://Stackoverflow.com/users/4711853', 'pm_score': 2, 'selected': False, 'text': '<p>Ok, there are some obvious example with reflection in this post, BUT reflection is usually slow, until you start to cache it properly.</p>\n\n<p>if you\'ll cache it properly, than it\'ll deep clone 1000000 object by 4,6s (measured by Watcher).</p>\n\n<pre><code>static readonly Dictionary&lt;Type, PropertyInfo[]&gt; ProperyList = new Dictionary&lt;Type, PropertyInfo[]&gt;();\n</code></pre>\n\n<p>than you take cached properties or add new to dictionary and use them simply</p>\n\n<pre><code>foreach (var prop in propList)\n{\n        var value = prop.GetValue(source, null);   \n        prop.SetValue(copyInstance, value, null);\n}\n</code></pre>\n\n<p>full code check in my post in another answer</p>\n\n<p><a href="https://stackoverflow.com/a/34365709/4711853">https://stackoverflow.com/a/34365709/4711853</a></p>\n'}, {'answer_id': 34998894, 'author': 'kalisohn', 'author_id': 2792931, 'author_profile': 'https://Stackoverflow.com/users/2792931', 'pm_score': 3, 'selected': False, 'text': '<p>As I couldn\'t find a cloner that meets all my requirements in different projects, I created a deep cloner that can be configured and adapted to different code structures instead of adapting my code to meet the cloners requirements. Its achieved by adding annotations to the code that shall be cloned or you just leave the code as it is to have the default behaviour. It uses reflection, type caches and is based on <a href="https://fasterflect.codeplex.com/" rel="noreferrer">fasterflect</a>. The cloning process is very fast for a huge amount of data and a high object hierarchy (compared to other reflection/serialization based algorithms). </p>\n\n<p><a href="https://github.com/kalisohn/CloneBehave" rel="noreferrer">https://github.com/kalisohn/CloneBehave</a></p>\n\n<p>Also available as a nuget package:\n<a href="https://www.nuget.org/packages/Clone.Behave/1.0.0" rel="noreferrer">https://www.nuget.org/packages/Clone.Behave/1.0.0</a></p>\n\n<p>For example: The following code will deepClone Address, but only perform a shallow copy of the _currentJob field. </p>\n\n<pre><code>public class Person \n{\n  [DeepClone(DeepCloneBehavior.Shallow)]\n  private Job _currentJob;      \n\n  public string Name { get; set; }\n\n  public Job CurrentJob \n  { \n    get{ return _currentJob; }\n    set{ _currentJob = value; }\n  }\n\n  public Person Manager { get; set; }\n}\n\npublic class Address \n{      \n  public Person PersonLivingHere { get; set; }\n}\n\nAddress adr = new Address();\nadr.PersonLivingHere = new Person("John");\nadr.PersonLivingHere.BestFriend = new Person("James");\nadr.PersonLivingHere.CurrentJob = new Job("Programmer");\n\nAddress adrClone = adr.Clone();\n\n//RESULT\nadr.PersonLivingHere == adrClone.PersonLivingHere //false\nadr.PersonLivingHere.Manager == adrClone.PersonLivingHere.Manager //false\nadr.PersonLivingHere.CurrentJob == adrClone.PersonLivingHere.CurrentJob //true\nadr.PersonLivingHere.CurrentJob.AnyProperty == adrClone.PersonLivingHere.CurrentJob.AnyProperty //true\n</code></pre>\n'}, {'answer_id': 36575152, 'author': 'GorvGoyl', 'author_id': 3073272, 'author_profile': 'https://Stackoverflow.com/users/3073272', 'pm_score': 3, 'selected': False, 'text': '<p>This method solved the problem for me:</p>\n\n<pre><code>private static MyObj DeepCopy(MyObj source)\n        {\n\n            var DeserializeSettings = new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace };\n\n            return JsonConvert.DeserializeObject&lt;MyObj &gt;(JsonConvert.SerializeObject(source), DeserializeSettings);\n\n        }\n</code></pre>\n\n<p>Use it like this: <code>MyObj a = DeepCopy(b);</code></p>\n'}, {'answer_id': 37498183, 'author': 'Stacked', 'author_id': 1372621, 'author_profile': 'https://Stackoverflow.com/users/1372621', 'pm_score': 4, 'selected': False, 'text': '<p>Keep things simple and use <a href="http://automapper.org/" rel="nofollow noreferrer">AutoMapper</a> as others mentioned, it\'s a simple little library to map one object to another... To copy an object to another with the same type, all you need is three lines of code:</p>\n\n<pre><code>MyType source = new MyType();\nMapper.CreateMap&lt;MyType, MyType&gt;();\nMyType target = Mapper.Map&lt;MyType, MyType&gt;(source);\n</code></pre>\n\n<p>The target object is now a copy of the source object.\nNot simple enough? Create an extension method to use everywhere in your solution:</p>\n\n<pre><code>public static T Copy&lt;T&gt;(this T source)\n{\n    T copy = default(T);\n    Mapper.CreateMap&lt;T, T&gt;();\n    copy = Mapper.Map&lt;T, T&gt;(source);\n    return copy;\n}\n</code></pre>\n\n<p>The extension method can be used as follow:</p>\n\n<pre><code>MyType copy = source.Copy();\n</code></pre>\n'}, {'answer_id': 37736016, 'author': 'Toxantron', 'author_id': 6082960, 'author_profile': 'https://Stackoverflow.com/users/6082960', 'pm_score': 3, 'selected': False, 'text': '<h1>Code Generator</h1>\n\n<p>We have seen a lot of ideas from serialization over manual implementation to reflection and I want to propose a totally different approach using the <a href="https://github.com/Toxantron/CGbR#cloneable" rel="noreferrer">CGbR Code Generator</a>. The generate clone method is memory and CPU efficient and therefor 300x faster as the standard DataContractSerializer.</p>\n\n<p>All you need is a partial class definition with <code>ICloneable</code> and the generator does the rest:</p>\n\n<pre><code>public partial class Root : ICloneable\n{\n    public Root(int number)\n    {\n        _number = number;\n    }\n    private int _number;\n\n    public Partial[] Partials { get; set; }\n\n    public IList&lt;ulong&gt; Numbers { get; set; }\n\n    public object Clone()\n    {\n        return Clone(true);\n    }\n\n    private Root()\n    {\n    }\n} \n\npublic partial class Root\n{\n    public Root Clone(bool deep)\n    {\n        var copy = new Root();\n        // All value types can be simply copied\n        copy._number = _number; \n        if (deep)\n        {\n            // In a deep clone the references are cloned \n            var tempPartials = new Partial[Partials.Length];\n            for (var i = 0; i &lt; Partials.Length; i++)\n            {\n                var value = Partials[i];\n                value = value.Clone(true);\n                tempPartials[i] = value;\n            }\n            copy.Partials = tempPartials;\n            var tempNumbers = new List&lt;ulong&gt;(Numbers.Count);\n            for (var i = 0; i &lt; Numbers.Count; i++)\n            {\n                var value = Numbers[i];\n                tempNumbers.Add(value);\n            }\n            copy.Numbers = tempNumbers;\n        }\n        else\n        {\n            // In a shallow clone only references are copied\n            copy.Partials = Partials; \n            copy.Numbers = Numbers; \n        }\n        return copy;\n    }\n}\n</code></pre>\n\n<p><strong>Note:</strong> Latest version has a more null checks, but I left them out for better understanding.</p>\n'}, {'answer_id': 38660465, 'author': 'Daniele D.', 'author_id': 4454567, 'author_profile': 'https://Stackoverflow.com/users/4454567', 'pm_score': 3, 'selected': False, 'text': "<p>Here a solution fast and easy that worked for me without relaying on Serialization/Deserialization. </p>\n\n<pre><code>public class MyClass\n{\n    public virtual MyClass DeepClone()\n    {\n        var returnObj = (MyClass)MemberwiseClone();\n        var type = returnObj.GetType();\n        var fieldInfoArray = type.GetRuntimeFields().ToArray();\n\n        foreach (var fieldInfo in fieldInfoArray)\n        {\n            object sourceFieldValue = fieldInfo.GetValue(this);\n            if (!(sourceFieldValue is MyClass))\n            {\n                continue;\n            }\n\n            var sourceObj = (MyClass)sourceFieldValue;\n            var clonedObj = sourceObj.DeepClone();\n            fieldInfo.SetValue(returnObj, clonedObj);\n        }\n        return returnObj;\n    }\n}\n</code></pre>\n\n<p><strong>EDIT</strong>:\nrequires </p>\n\n<pre><code>    using System.Linq;\n    using System.Reflection;\n</code></pre>\n\n<p>That's How I used it</p>\n\n<pre><code>public MyClass Clone(MyClass theObjectIneededToClone)\n{\n    MyClass clonedObj = theObjectIneededToClone.DeepClone();\n}\n</code></pre>\n"}, {'answer_id': 38754644, 'author': 'frakon', 'author_id': 2094687, 'author_profile': 'https://Stackoverflow.com/users/2094687', 'pm_score': 5, 'selected': False, 'text': '<p>The best is to implement an <strong>extension method</strong> like</p>\n\n<pre><code>public static T DeepClone&lt;T&gt;(this T originalObject)\n{ /* the cloning code */ }\n</code></pre>\n\n<p>and then use it anywhere in the solution by</p>\n\n<pre><code>var copy = anyObject.DeepClone();\n</code></pre>\n\n<p>We can have the following three implementations:</p>\n\n<ol>\n<li><a href="https://stackoverflow.com/a/129395/2094687"><strong>By Serialization</strong></a> (the shortest code)</li>\n<li><a href="https://github.com/Burtsev-Alexey/net-object-deep-copy/" rel="noreferrer"><strong>By Reflection</strong></a> - <strong>5x faster</strong></li>\n<li><a href="http://www.codeproject.com/Articles/1111658/Fast-Deep-Copy-by-Expression-Trees-C-Sharp" rel="noreferrer"><strong>By Expression Trees</strong></a> - <strong>20x faster</strong></li>\n</ol>\n\n<p>All linked methods are well working and were deeply tested.</p>\n'}, {'answer_id': 39044123, 'author': 'Sudhanva Kotabagi', 'author_id': 5198209, 'author_profile': 'https://Stackoverflow.com/users/5198209', 'pm_score': 2, 'selected': False, 'text': '<p>I think you can try this.</p>\n\n<pre><code>MyObject myObj = GetMyObj(); // Create and fill a new object\nMyObject newObj = new MyObject(myObj); //DeepClone it\n</code></pre>\n'}, {'answer_id': 41988090, 'author': 'gaa', 'author_id': 1842492, 'author_profile': 'https://Stackoverflow.com/users/1842492', 'pm_score': -1, 'selected': False, 'text': '<p>I know that this question and <a href="https://stackoverflow.com/a/78612/1842492">answer</a> sits here for a while and following is not quite answer but rather observation, to which I came across recently when I was checking whether indeed privates are not being cloned (I wouldn\'t be myself if I have not ;) when I happily copy-pasted @johnc <a href="https://stackoverflow.com/a/78612/1842492">updated answer</a>.</p>\n\n<p>I simply made myself extension method (which is pretty much copy-pasted form aforementioned answer):</p>\n\n<pre><code>public static class CloneThroughJsonExtension\n{\n    private static readonly JsonSerializerSettings DeserializeSettings = new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace };\n\n    public static T CloneThroughJson&lt;T&gt;(this T source)\n    {\n        return ReferenceEquals(source, null) ? default(T) : JsonConvert.DeserializeObject&lt;T&gt;(JsonConvert.SerializeObject(source), DeserializeSettings);\n    }\n}\n</code></pre>\n\n<p>and dropped naively class like this (in fact there was more of those but they are unrelated):</p>\n\n<pre><code>public class WhatTheHeck\n{\n    public string PrivateSet { get; private set; } // matches ctor param name\n\n    public string GetOnly { get; } // matches ctor param name\n\n    private readonly string _indirectField;\n    public string Indirect =&gt; $"Inception of: {_indirectField} "; // matches ctor param name\n    public string RealIndirectFieldVaule =&gt; _indirectField;\n\n    public WhatTheHeck(string privateSet, string getOnly, string indirect)\n    {\n        PrivateSet = privateSet;\n        GetOnly = getOnly;\n        _indirectField = indirect;\n    }\n}\n</code></pre>\n\n<p>and code like this:</p>\n\n<pre><code>var clone = new WhatTheHeck("Private-Set-Prop cloned!", "Get-Only-Prop cloned!", "Indirect-Field clonned!").CloneThroughJson();\nConsole.WriteLine($"1. {clone.PrivateSet}");\nConsole.WriteLine($"2. {clone.GetOnly}");\nConsole.WriteLine($"3.1. {clone.Indirect}");\nConsole.WriteLine($"3.2. {clone.RealIndirectFieldVaule}");\n</code></pre>\n\n<p>resulted in:</p>\n\n<pre><code>1. Private-Set-Prop cloned!\n2. Get-Only-Prop cloned!\n3.1. Inception of: Inception of: Indirect-Field cloned!\n3.2. Inception of: Indirect-Field cloned!\n</code></pre>\n\n<p>I was whole like: WHAT THE F... so I grabbed Newtonsoft.Json Github repo and started to dig.\nWhat it comes out, is that: while deserializing a type which happens to have only one ctor and its param names match (<a href="https://github.com/JamesNK/Newtonsoft.Json/blob/cf6a917a46b532558578c53d34cdc4f39ec0560a/Src/Newtonsoft.Json/Serialization/JsonPropertyCollection.cs#L126" rel="nofollow noreferrer">case insensitive</a>) public property names they will be passed to ctor as those params. Some clues can be found in the code <a href="https://github.com/JamesNK/Newtonsoft.Json/blob/744be1a712ee0e0bbc264b800368a7b7f5026884/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs#L606" rel="nofollow noreferrer">here</a> and <a href="https://github.com/JamesNK/Newtonsoft.Json/blob/744be1a712ee0e0bbc264b800368a7b7f5026884/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs#L309" rel="nofollow noreferrer">here</a>.</p>\n\n<p><strong>Bottom line</strong></p>\n\n<p>I know that it is rather not common case and example code is bit abusive, but hey! It got me by surprise when I was checking whether there is any dragon waiting in the bushes to jump out and bite me in the ass. ;)</p>\n'}, {'answer_id': 43569318, 'author': 'Mauro Sampietro', 'author_id': 711061, 'author_profile': 'https://Stackoverflow.com/users/711061', 'pm_score': 2, 'selected': False, 'text': '<p>A mapper performs a deep-copy. Foreach member of your object it creates a new object and assign all of its values. It works recursively on each non-primitive inner member.</p>\n\n<p>I suggest you one of the fastest, currently actively developed ones.\nI suggest UltraMapper <a href="https://github.com/maurosampietro/UltraMapper" rel="nofollow noreferrer">https://github.com/maurosampietro/UltraMapper</a></p>\n\n<p>Nuget packages: <a href="https://www.nuget.org/packages/UltraMapper/" rel="nofollow noreferrer">https://www.nuget.org/packages/UltraMapper/</a></p>\n'}, {'answer_id': 45557629, 'author': 'lindexi', 'author_id': 6116637, 'author_profile': 'https://Stackoverflow.com/users/6116637', 'pm_score': 1, 'selected': False, 'text': '<p>I found a new way to do it that is Emit.</p>\n\n<p>We can use Emit to add the IL to app and run it. But I dont think its a good way for I want to perfect this that I write my answer.</p>\n\n<p>The Emit can see the <a href="https://msdn.microsoft.com/en-us/library/system.reflection.emit(v=vs.110).aspx" rel="nofollow noreferrer">official document</a> and <a href="http://www.c-sharpcorner.com/uploadfile/puranindia/reflection-and-reflection-emit-in-C-Sharp/" rel="nofollow noreferrer">Guide</a></p>\n\n<p>You should learn some IL to read the code. I will write the code that can copy the property in class.</p>\n\n<pre><code>public static class Clone\n{        \n    // ReSharper disable once InconsistentNaming\n    public static void CloneObjectWithIL&lt;T&gt;(T source, T los)\n    {\n        //see http://lindexi.oschina.io/lindexi/post/C-%E4%BD%BF%E7%94%A8Emit%E6%B7%B1%E5%85%8B%E9%9A%86/\n        if (CachedIl.ContainsKey(typeof(T)))\n        {\n            ((Action&lt;T, T&gt;) CachedIl[typeof(T)])(source, los);\n            return;\n        }\n        var dynamicMethod = new DynamicMethod("Clone", null, new[] { typeof(T), typeof(T) });\n        ILGenerator generator = dynamicMethod.GetILGenerator();\n\n        foreach (var temp in typeof(T).GetProperties().Where(temp =&gt; temp.CanRead &amp;&amp; temp.CanWrite))\n        {\n            //do not copy static that will except\n            if (temp.GetAccessors(true)[0].IsStatic)\n            {\n                continue;\n            }\n\n            generator.Emit(OpCodes.Ldarg_1);// los\n            generator.Emit(OpCodes.Ldarg_0);// s\n            generator.Emit(OpCodes.Callvirt, temp.GetMethod);\n            generator.Emit(OpCodes.Callvirt, temp.SetMethod);\n        }\n        generator.Emit(OpCodes.Ret);\n        var clone = (Action&lt;T, T&gt;) dynamicMethod.CreateDelegate(typeof(Action&lt;T, T&gt;));\n        CachedIl[typeof(T)] = clone;\n        clone(source, los);\n    }\n\n    private static Dictionary&lt;Type, Delegate&gt; CachedIl { set; get; } = new Dictionary&lt;Type, Delegate&gt;();\n}\n</code></pre>\n\n<p>The code can be deep copy but it can copy the property. If you want to make it to deep copy that you can change it for the IL is too hard that I cant do it.</p>\n'}, {'answer_id': 49276795, 'author': 'Matthew Watson', 'author_id': 106159, 'author_profile': 'https://Stackoverflow.com/users/106159', 'pm_score': 2, 'selected': False, 'text': "<p>Yet another JSON.NET answer. This version works with classes that don't implement ISerializable.</p>\n\n<pre><code>public static class Cloner\n{\n    public static T Clone&lt;T&gt;(T source)\n    {\n        if (ReferenceEquals(source, null))\n            return default(T);\n\n        var settings = new JsonSerializerSettings { ContractResolver = new ContractResolver() };\n\n        return JsonConvert.DeserializeObject&lt;T&gt;(JsonConvert.SerializeObject(source, settings), settings);\n    }\n\n    class ContractResolver : DefaultContractResolver\n    {\n        protected override IList&lt;JsonProperty&gt; CreateProperties(Type type, MemberSerialization memberSerialization)\n        {\n            var props = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)\n                .Select(p =&gt; base.CreateProperty(p, memberSerialization))\n                .Union(type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)\n                    .Select(f =&gt; base.CreateProperty(f, memberSerialization)))\n                .ToList();\n            props.ForEach(p =&gt; { p.Writable = true; p.Readable = true; });\n            return props;\n        }\n    }\n}\n</code></pre>\n"}, {'answer_id': 50150204, 'author': 'Sameera R.', 'author_id': 2016932, 'author_profile': 'https://Stackoverflow.com/users/2016932', 'pm_score': 1, 'selected': False, 'text': '<p>C# Extension that\'ll support for "not <strong>ISerializable</strong>" types too.</p>\n\n<pre><code> public static class AppExtensions\n {                                                                      \n       public static T DeepClone&lt;T&gt;(this T a)\n       {\n           using (var stream = new MemoryStream())\n           {\n               var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));\n\n               serializer.Serialize(stream, a);\n               stream.Position = 0;\n               return (T)serializer.Deserialize(stream);\n           }\n       }                                                                    \n }\n</code></pre>\n\n<p>Usage</p>\n\n<pre><code>       var obj2 = obj1.DeepClone()\n</code></pre>\n'}, {'answer_id': 52780057, 'author': 'qubits', 'author_id': 1444319, 'author_profile': 'https://Stackoverflow.com/users/1444319', 'pm_score': 2, 'selected': False, 'text': "<p>The generic approaches are all technically valid, but I just wanted to add a note from myself since we rarely actually need a real deep copy, and I would strongly oppose using generic deep copying in actual business applications since that makes it so you might have many places where the objects are copied and then modified explicitly, its easy to get lost. </p>\n\n<p>In most real-life situations also you want to have as much granular control over the copying process as possible since you are not only coupled to the data access framework but also in practice the copied business objects should rarely be 100% the same. Think an example  referenceId's used by the ORM to identify object references, a full deep copy will also copy this id's so while in-memory the objects will be different, as soon as you submit it to the datastore, it will complain, so you will have to modify this properties manually after copying anyway and if the object changes you need to adjust it in all of the places which use the generic deep copying.</p>\n\n<p>Expanding on @cregox answer with ICloneable, what actually is a deep copy? Its just a newly allocated object on the heap that is identical to the original object but occupies a different memory space, as such rather than using a generic cloner functionality why not just create a new object?</p>\n\n<p>I personally use the idea of static factory methods on my domain objects.</p>\n\n<p>Example:</p>\n\n<pre><code>    public class Client\n    {\n        public string Name { get; set; }\n\n        protected Client()\n        {\n        }\n\n        public static Client Clone(Client copiedClient)\n        {\n            return new Client\n            {\n                Name = copiedClient.Name\n            };\n        }\n    }\n\n    public class Shop\n    {\n        public string Name { get; set; }\n\n        public string Address { get; set; }\n\n        public ICollection&lt;Client&gt; Clients { get; set; }\n\n        public static Shop Clone(Shop copiedShop, string newAddress, ICollection&lt;Client&gt; clients)\n        {\n            var copiedClients = new List&lt;Client&gt;();\n            foreach (var client in copiedShop.Clients)\n            {\n                copiedClients.Add(Client.Clone(client));\n            }\n\n            return new Shop\n            {\n                Name = copiedShop.Name,\n                Address = newAddress,\n                Clients = copiedClients\n            };\n        }\n    }\n</code></pre>\n\n<p>If someone is looking how he can structure object instantiation while retaining full control over the copying process that's a solution that I have been personally very successful with. The protected constructors also make it so, other developers are forced to use the factory methods which gives a neat single point of object instantiation encapsulating the construction logic inside of the object. You can also overload the method and have several clone logic's for different places if necessary.</p>\n"}, {'answer_id': 53332691, 'author': 'Michael Brown', 'author_id': 1395182, 'author_profile': 'https://Stackoverflow.com/users/1395182', 'pm_score': 3, 'selected': False, 'text': '<p>As nearly all of the answers to this question have been unsatisfactory or plainly don\'t work in my situation, I have authored <a href="https://github.com/replaysMike/AnyClone" rel="noreferrer">AnyClone</a> which is entirely implemented with reflection and solved all of the needs here. I was unable to get serialization to work in a complicated scenario with complex structure, and <code>IClonable</code> is less than ideal - in fact it shouldn\'t even be necessary.</p>\n\n<p>Standard ignore attributes are supported using <code>[IgnoreDataMember]</code>, <code>[NonSerialized]</code>. Supports complex collections, properties without setters, readonly fields etc.</p>\n\n<p>I hope it helps someone else out there who ran into the same problems I did.</p>\n'}, {'answer_id': 56691124, 'author': 'Ted Mucuzany', 'author_id': 11652382, 'author_profile': 'https://Stackoverflow.com/users/11652382', 'pm_score': 2, 'selected': False, 'text': '<p>Deep cloning is about copying <strong>state</strong>. For <code>.net</code> <strong>state</strong> means <strong>fields</strong>.</p>\n\n<p>Let\'s say one have an hierarchy:</p>\n\n<pre><code>static class RandomHelper\n{\n    private static readonly Random random = new Random();\n\n    public static int Next(int maxValue) =&gt; random.Next(maxValue);\n}\n\nclass A\n{\n    private readonly int random = RandomHelper.Next(100);\n\n    public override string ToString() =&gt; $"{typeof(A).Name}.{nameof(random)} = {random}";\n}\n\nclass B : A\n{\n    private readonly int random = RandomHelper.Next(100);\n\n    public override string ToString() =&gt; $"{typeof(B).Name}.{nameof(random)} = {random} {base.ToString()}";\n}\n\nclass C : B\n{\n    private readonly int random = RandomHelper.Next(100);\n\n    public override string ToString() =&gt; $"{typeof(C).Name}.{nameof(random)} = {random} {base.ToString()}";\n}\n</code></pre>\n\n<p>Cloning can be done:</p>\n\n<pre><code>static class DeepCloneExtension\n{\n    // consider instance fields, both public and non-public\n    private static readonly BindingFlags bindingFlags =\n        BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;\n\n    public static T DeepClone&lt;T&gt;(this T obj) where T : new()\n    {\n        var type = obj.GetType();\n        var result = (T)Activator.CreateInstance(type);\n\n        do\n            // copy all fields\n            foreach (var field in type.GetFields(bindingFlags))\n                field.SetValue(result, field.GetValue(obj));\n        // for every level of hierarchy\n        while ((type = type.BaseType) != typeof(object));\n\n        return result;\n    }\n}\n</code></pre>\n\n<p><strong>Demo1</strong>:</p>\n\n<pre><code>Console.WriteLine(new C());\nConsole.WriteLine(new C());\n\nvar c = new C();\nConsole.WriteLine($"{Environment.NewLine}Image: {c}{Environment.NewLine}");\n\nConsole.WriteLine(new C());\nConsole.WriteLine(new C());\n\nConsole.WriteLine($"{Environment.NewLine}Clone: {c.DeepClone()}{Environment.NewLine}");\n\nConsole.WriteLine(new C());\nConsole.WriteLine(new C());\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>C.random = 92 B.random = 66 A.random = 71\nC.random = 36 B.random = 64 A.random = 17\n\nImage: C.random = 96 B.random = 18 A.random = 46\n\nC.random = 60 B.random = 7 A.random = 37\nC.random = 78 B.random = 11 A.random = 18\n\nClone: C.random = 96 B.random = 18 A.random = 46\n\nC.random = 33 B.random = 63 A.random = 38\nC.random = 4 B.random = 5 A.random = 79\n</code></pre>\n\n<p>Notice, all new objects have random values for <code>random</code> field, but <code>clone</code> exactly matches the <code>image</code></p>\n\n<p><strong>Demo2</strong>:</p>\n\n<pre><code>class D\n{\n    public event EventHandler Event;\n    public void RaiseEvent() =&gt; Event?.Invoke(this, EventArgs.Empty);\n}\n\n// ...\n\nvar image = new D();\nConsole.WriteLine($"Created obj #{image.GetHashCode()}");\n\nimage.Event += (sender, e) =&gt; Console.WriteLine($"Event from obj #{sender.GetHashCode()}");\nConsole.WriteLine($"Subscribed to event of obj #{image.GetHashCode()}");\n\nimage.RaiseEvent();\nimage.RaiseEvent();\n\nvar clone = image.DeepClone();\nConsole.WriteLine($"obj #{image.GetHashCode()} cloned to obj #{clone.GetHashCode()}");\n\nclone.RaiseEvent();\nimage.RaiseEvent();\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>Created obj #46104728\nSubscribed to event of obj #46104728\nEvent from obj #46104728\nEvent from obj #46104728\nobj #46104728 cloned to obj #12289376\nEvent from obj #12289376\nEvent from obj #46104728\n</code></pre>\n\n<p>Notice, event backing field is copied too and client is subscribed to clone\'s event too.</p>\n'}, {'answer_id': 56805986, 'author': 'Konrad', 'author_id': 2828480, 'author_profile': 'https://Stackoverflow.com/users/2828480', 'pm_score': 1, 'selected': False, 'text': '<p>Using <code>System.Text.Json</code>:</p>\n\n<p><a href="https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/" rel="nofollow noreferrer">https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/</a></p>\n\n<pre><code>public static T DeepCopy&lt;T&gt;(this T source)\n{\n    return source == null ? default : JsonSerializer.Parse&lt;T&gt;(JsonSerializer.ToString(source));\n}\n</code></pre>\n\n<p>The new API is using <code>Span&lt;T&gt;</code>. This should be fast, would be nice to do some benchmarks.</p>\n\n<p><strong>Note:</strong> there\'s no need for <code>ObjectCreationHandling.Replace</code> like in Json.NET as it will replace collection values by default. You should forget about Json.NET now as everything is going to be replaced with the new official API.</p>\n\n<p>I\'m not sure this will work with private fields.</p>\n'}, {'answer_id': 56933017, 'author': 'alelom', 'author_id': 3873799, 'author_profile': 'https://Stackoverflow.com/users/3873799', 'pm_score': 5, 'selected': False, 'text': '<h2>DeepCloner: Quick, easy, effective NuGet package to solve cloning</h2>\n\n<p>After reading all answers I was surprised no one mentioned this excellent package: </p>\n\n<p><a href="https://github.com/force-net/DeepCloner" rel="noreferrer">DeepCloner GitHub project</a>  </p>\n\n<p><a href="https://www.nuget.org/packages/DeepCloner" rel="noreferrer">DeepCloner NuGet package</a></p>\n\n<p>Elaborating a bit on its README, here are the reason why we chose it at work:</p>\n\n<blockquote>\n  <ul>\n  <li>It can deep or shallow copy </li>\n  <li>In deep cloning all object graph is maintained. </li>\n  <li>Uses code-generation in runtime, as result cloning is blazingly fast</li>\n  <li>Objects copied by internal structure, no methods or ctors called</li>\n  <li>You don\'t need to mark classes somehow (like Serializable-attribute, or implement interfaces)</li>\n  <li>No requirement to specify object type for cloning. Object can be casted to interface or as an abstract object (e.g. you can clone array of ints as abstract Array or IEnumerable; even null can be cloned without any errors)</li>\n  <li>Cloned object doesn\'t have any ability to determine that he is clone (except with very specific methods)</li>\n  </ul>\n</blockquote>\n\n<h3>Usage:</h3>\n\n<pre class="lang-cs prettyprint-override"><code>var deepClone = new { Id = 1, Name = "222" }.DeepClone();\nvar shallowClone = new { Id = 1, Name = "222" }.ShallowClone();\n</code></pre>\n\n<h3>Performance:</h3>\n\n<p>The README contains a performance comparison of various cloning libraries and methods: <a href="https://github.com/force-net/DeepCloner#performance" rel="noreferrer">DeepCloner Performance</a>.</p>\n\n<h3>Requirements:</h3>\n\n<ul>\n<li><em>.NET 4.0 or higher or .NET Standard 1.3 (.NET Core)</em></li>\n<li><em>Requires Full Trust permission set or Reflection permission (MemberAccess)</em></li>\n</ul>\n'}, {'answer_id': 57279815, 'author': 'Marcell Toth', 'author_id': 10614791, 'author_profile': 'https://Stackoverflow.com/users/10614791', 'pm_score': 4, 'selected': False, 'text': '<p><em>Disclaimer: I\'m the author of the mentioned package.</em></p>\n\n<p>I was surprised how the top answers to this question in 2019 still use serialization or reflection. </p>\n\n<h2>Serialization is limiting (requires attributes, specific constructors, etc.) and is very slow</h2>\n\n<p><code>BinaryFormatter</code> requires the <code>Serializable</code> attribute, <code>JsonConverter</code> requires a parameterless constructor or attributes, neither handle read only fields or interfaces very well and both are 10-30x slower than necessary.</p>\n\n<h2>Expression Trees</h2>\n\n<p>You can instead use <em>Expression Trees</em> or <em>Reflection.Emit</em> to generate cloning code only once, then use that compiled code instead of slow reflection or serialization.</p>\n\n<p>Having come across the problem myself and seeing no satisfactory solution, I decided to create a package that does just that and <strong>works with every type and is a almost as fast as custom written code</strong>.</p>\n\n<p>You can find the project on GitHub: <a href="https://github.com/marcelltoth/ObjectCloner" rel="noreferrer">https://github.com/marcelltoth/ObjectCloner</a></p>\n\n<h2>Usage</h2>\n\n<p>You can install it from NuGet. Either get the <code>ObjectCloner</code> package and use it as:</p>\n\n<pre class="lang-cs prettyprint-override"><code>var clone = ObjectCloner.DeepClone(original);\n</code></pre>\n\n<p>or if you don\'t mind polluting your object type with extensions get <code>ObjectCloner.Extensions</code> as well and write:</p>\n\n<pre class="lang-cs prettyprint-override"><code>var clone = original.DeepClone();\n</code></pre>\n\n<h2>Performance</h2>\n\n<p>A simple benchmark of cloning a class hierarchy showed performance ~3x faster than using Reflection, ~12x faster than Newtonsoft.Json serialization and ~36x faster than the highly suggested <code>BinaryFormatter</code>.</p>\n'}, {'answer_id': 58975653, 'author': 'Erçin Dedeoğlu', 'author_id': 2426367, 'author_profile': 'https://Stackoverflow.com/users/2426367', 'pm_score': 2, 'selected': False, 'text': '<p>Shortest way but need dependency:</p>\n\n<pre><code>using Newtonsoft.Json;\n    public static T Clone&lt;T&gt;(T source) =&gt;\n        JsonConvert.DeserializeObject&lt;T&gt;(JsonConvert.SerializeObject(source));\n</code></pre>\n'}, {'answer_id': 61976233, 'author': 'Hidayet R. Colkusu', 'author_id': 8614792, 'author_profile': 'https://Stackoverflow.com/users/8614792', 'pm_score': 0, 'selected': False, 'text': '<p>For the cloning process, the object can be converted to the byte array first and then converted back to the object.</p>\n\n<pre><code>public static class Extentions\n{\n    public static T Clone&lt;T&gt;(this T obj)\n    {\n        byte[] buffer = BinarySerialize(obj);\n        return (T)BinaryDeserialize(buffer);\n    }\n\n    public static byte[] BinarySerialize(object obj)\n    {\n        using (var stream = new MemoryStream())\n        {\n            var formatter = new BinaryFormatter(); \n            formatter.Serialize(stream, obj); \n            return stream.ToArray();\n        }\n    }\n\n    public static object BinaryDeserialize(byte[] buffer)\n    {\n        using (var stream = new MemoryStream(buffer))\n        {\n           var formatter = new BinaryFormatter(); \n           return formatter.Deserialize(stream);\n        }\n    }\n}\n</code></pre>\n\n<p>The object must be serialized for the serialization process.</p>\n\n<pre><code>[Serializable]\npublic class MyObject\n{\n    public string Name  { get; set; }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>MyObject myObj  = GetMyObj();\nMyObject newObj = myObj.Clone();\n</code></pre>\n'}, {'answer_id': 62564309, 'author': 'Sean McAvoy', 'author_id': 12367139, 'author_profile': 'https://Stackoverflow.com/users/12367139', 'pm_score': 3, 'selected': False, 'text': '<p>Create an extension:</p>\n<pre><code>public static T Clone&lt;T&gt;(this T theObject)\n{\n    string jsonData = JsonConvert.SerializeObject(theObject);\n    return JsonConvert.DeserializeObject&lt;T&gt;(jsonData);\n}\n</code></pre>\n<p>And call it like this:</p>\n<pre><code>NewObject = OldObject.Clone();\n</code></pre>\n'}, {'answer_id': 66538192, 'author': 'Ogglas', 'author_id': 3850405, 'author_profile': 'https://Stackoverflow.com/users/3850405', 'pm_score': 0, 'selected': False, 'text': '<p>An addition to @Konrad and @craastad with using built in <code>System.Text.Json</code> for <code>.NET &gt;5</code></p>\n<p><a href="https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-5-0" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-5-0</a></p>\n<p>Method:</p>\n<pre><code>public static T Clone&lt;T&gt;(T source)\n{\n    var serialized = JsonSerializer.Serialize(source);\n    return JsonSerializer.Deserialize&lt;T&gt;(serialized);\n}\n</code></pre>\n<p>Extension method:</p>\n<pre><code>public static class SystemExtension\n{\n    public static T Clone&lt;T&gt;(this T source)\n    {\n        var serialized = JsonSerializer.Serialize(source);\n        return JsonSerializer.Deserialize&lt;T&gt;(serialized);\n    }\n}\n</code></pre>\n'}, {'answer_id': 67402990, 'author': 'Adel Tabareh', 'author_id': 5007985, 'author_profile': 'https://Stackoverflow.com/users/5007985', 'pm_score': 1, 'selected': False, 'text': '<p>using System.Text.Json;</p>\n<pre><code>public static class CloneExtensions\n{\n    public static T Clone&lt;T&gt;(this T cloneable) where T : new()\n    {\n        var toJson = JsonSerializer.Serialize(cloneable);\n        return JsonSerializer.Deserialize&lt;T&gt;(toJson);\n    }\n}\n</code></pre>\n'}, {'answer_id': 68663921, 'author': 'Izzy', 'author_id': 1918179, 'author_profile': 'https://Stackoverflow.com/users/1918179', 'pm_score': 2, 'selected': False, 'text': '<p>C# 9.0 is introducing the <code>with</code> keyword that requires a <code>record</code> (Thanks Mark Nading). This should allow very simple object cloning (and mutation if required) with very little boilerplate, but only with a <code>record</code>.</p>\n<p>You cannot seem to be able to clone (by value) a class by putting it into a generic <code>record</code>;</p>\n<pre><code>using System;\n                \npublic class Program\n{\n    public class Example\n    {\n        public string A { get; set; }\n    }\n    \n    public record ClonerRecord&lt;T&gt;(T a)\n    {\n    }\n\n    public static void Main()\n    {\n        var foo = new Example {A = &quot;Hello World&quot;};\n        var bar = (new ClonerRecord&lt;Example&gt;(foo) with {}).a;\n        foo.A = &quot;Goodbye World :(&quot;;\n        Console.WriteLine(bar.A);\n    }\n}\n</code></pre>\n<p>This writes &quot;Goodbye World :(&quot;- the string was copied by reference (undesired). <a href="https://dotnetfiddle.net/w3IJgG" rel="nofollow noreferrer">https://dotnetfiddle.net/w3IJgG</a></p>\n<p>(Incredibly, the above works correctly with a <code>struct</code>! <a href="https://dotnetfiddle.net/469NJv" rel="nofollow noreferrer">https://dotnetfiddle.net/469NJv</a>)</p>\n<p>But cloning a <code>record</code> does seem to work as indented, cloning by value.</p>\n<pre><code>using System;\n\npublic class Program\n{\n    public record Example\n    {\n        public string A { get; set; }\n    }\n    \n    public static void Main()\n    {\n        var foo = new Example {A = &quot;Hello World&quot;};\n        var bar = foo with {};\n        foo.A = &quot;Goodbye World :(&quot;;\n        Console.WriteLine(bar.A);\n    }\n}\n</code></pre>\n<p>This returns &quot;Hello World&quot;, the string was copied by value! <a href="https://dotnetfiddle.net/MCHGEL" rel="nofollow noreferrer">https://dotnetfiddle.net/MCHGEL</a></p>\n<p>More information can be found on the blog post:</p>\n<p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/with-expression" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/with-expression</a></p>\n'}, {'answer_id': 69211283, 'author': 'Cinorid', 'author_id': 6338072, 'author_profile': 'https://Stackoverflow.com/users/6338072', 'pm_score': 1, 'selected': False, 'text': '<p>I did some benchmark on current answers and found some interesting facts.</p>\n<p>Using BinarySerializer         =&gt; <a href="https://stackoverflow.com/a/78612/6338072">https://stackoverflow.com/a/78612/6338072</a></p>\n<p>Using XmlSerializer            =&gt; <a href="https://stackoverflow.com/a/50150204/6338072">https://stackoverflow.com/a/50150204/6338072</a></p>\n<p>Using Activator.CreateInstance =&gt; <a href="https://stackoverflow.com/a/56691124/6338072">https://stackoverflow.com/a/56691124/6338072</a></p>\n<p>These are the results</p>\n<pre><code>BenchmarkDotNet=v0.13.1, OS=Windows 10.0.18363.1734 (1909/November2019Update/19H2)\n</code></pre>\n<p>Intel Core i5-6200U CPU 2.30GHz (Skylake), 1 CPU, 4 logical and 2 physical cores\n[Host]     : .NET Framework 4.8 (4.8.4400.0), X86 LegacyJIT\nDefaultJob : .NET Framework 4.8 (4.8.4400.0), X86 LegacyJIT</p>\n<div class="s-table-container">\n<table class="s-table">\n<thead>\n<tr>\n<th>Method</th>\n<th style="text-align: right;">Mean</th>\n<th style="text-align: right;">Error</th>\n<th style="text-align: right;">StdDev</th>\n<th style="text-align: right;">Gen 0</th>\n<th style="text-align: right;">Allocated</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>BinarySerializer</td>\n<td style="text-align: right;">220.69 us</td>\n<td style="text-align: right;">4.374 us</td>\n<td style="text-align: right;">9.963 us</td>\n<td style="text-align: right;">49.8047</td>\n<td style="text-align: right;">77 KB</td>\n</tr>\n<tr>\n<td>XmlSerializer</td>\n<td style="text-align: right;">182.72 us</td>\n<td style="text-align: right;">3.619 us</td>\n<td style="text-align: right;">9.405 us</td>\n<td style="text-align: right;">21.9727</td>\n<td style="text-align: right;">34 KB</td>\n</tr>\n<tr>\n<td>Activator.CreateInstance</td>\n<td style="text-align: right;">49.99 us</td>\n<td style="text-align: right;">0.992 us</td>\n<td style="text-align: right;">2.861 us</td>\n<td style="text-align: right;">1.9531</td>\n<td style="text-align: right;">3 KB</td>\n</tr>\n</tbody>\n</table>\n</div>'}, {'answer_id': 69471766, 'author': 'ʞᴉɯ', 'author_id': 182331, 'author_profile': 'https://Stackoverflow.com/users/182331', 'pm_score': -1, 'selected': False, 'text': '<p>Found this package, who seems quicker of <code>DeepCloner</code>, and with no dependencies, compared to it.</p>\n<p><a href="https://github.com/AlenToma/FastDeepCloner" rel="nofollow noreferrer">https://github.com/AlenToma/FastDeepCloner</a></p>\n'}, {'answer_id': 70899238, 'author': 'vivek nuna', 'author_id': 6527049, 'author_profile': 'https://Stackoverflow.com/users/6527049', 'pm_score': 2, 'selected': False, 'text': '<p>I’ll use the below simple way to implement this.\nJust create an abstract class and implement method to serialize and deserialize again and return.</p>\n<pre><code>public abstract class CloneablePrototype&lt;T&gt;\n{\n    public T DeepCopy()\n    {\n        string result = JsonConvert.SerializeObject(this);\n        return JsonConvert.DeserializeObject&lt;T&gt;(result);\n    }\n}\npublic class YourClass : CloneablePrototype&lt; YourClass&gt;\n…\n…\n…\n</code></pre>\n<p>And the use it like this to create deep copy.</p>\n<pre><code>YourClass newObj = (YourClass)oldObj.DeepCopy();\n</code></pre>\n<p>This solution is easy to extend as well if you need to implement the shallow copy method as well.</p>\n<p>Just implement a new method in the abstract class.</p>\n<pre><code>public T ShallowCopy()\n{\n    return (T)this.MemberwiseClone();\n}\n</code></pre>\n'}, {'answer_id': 71863562, 'author': 'David Oganov', 'author_id': 7741097, 'author_profile': 'https://Stackoverflow.com/users/7741097', 'pm_score': 2, 'selected': False, 'text': '<p>Besides some of the brilliant answers here, what you can do in C# 9.0 &amp; higher, is the following (assuming you can convert your class to a record):</p>\n<pre><code>record Record\n{\n    public int Property1 { get; set; }\n\n    public string Property2 { get; set; }\n}\n</code></pre>\n<p>And then, simply use <a href="https://stackoverflow.com/questions/69616749/what-is-the-with-operator-for-in-c">with operator</a> to copy values of one object to the new one.</p>\n<pre><code>var object1 = new Record()\n{\n    Property1 = 1,\n    Property2 = &quot;2&quot;\n};\n\nvar object2 = object1 with { };\n// object2 now has Property1 = 1 &amp; Property2 = &quot;2&quot;\n</code></pre>\n<p>I hope this helps :)</p>\n'}, {'answer_id': 73228716, 'author': 'Efreeto', 'author_id': 2680660, 'author_profile': 'https://Stackoverflow.com/users/2680660', 'pm_score': 0, 'selected': False, 'text': "<p>Building upon @craastad's answer, for derived classes.</p>\n<p>In the original answer, if the caller is calling <code>DeepCopy</code> on a base class object, the cloned object is of a base class. But the following code will return the derived class.</p>\n<pre><code>using Newtonsoft.Json;\n\npublic static T DeepCopy&lt;T&gt;(this T source)\n{\n    return (T)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(source), source.GetType());\n}\n</code></pre>\n"}, {'answer_id': 73300838, 'author': 'Adamy', 'author_id': 657926, 'author_profile': 'https://Stackoverflow.com/users/657926', 'pm_score': -1, 'selected': False, 'text': "<p>If you use net.core and the object is serializable, you can use</p>\n<pre><code>var jsonBin = BinaryData.FromObjectAsJson(yourObject);\n</code></pre>\n<p>then</p>\n<pre><code>var yourObjectCloned = jsonBin.ToObjectFromJson&lt;YourType&gt;();\n</code></pre>\n<p>BinaryData is in dotnet therefore you don't need a third party lib. It also can handle the situation that the property on your class is Object type (the actual data in your property still need to be serializable)</p>\n"}, {'answer_id': 73580774, 'author': 'Daniel Jonsson', 'author_id': 595990, 'author_profile': 'https://Stackoverflow.com/users/595990', 'pm_score': 2, 'selected': False, 'text': '<p>In the codebase I am working with, we had a copy of the file <code>ObjectExtensions.cs</code> from the GitHub project <a href="https://github.com/Burtsev-Alexey/net-object-deep-copy/blob/master/ObjectExtensions.cs" rel="nofollow noreferrer">Burtsev-Alexey/net-object-deep-copy</a>. It is 9 years old. It worked, although we later realized it was very slow for larger object structures.</p>\n<p>Instead, we found a fork of the file <code>ObjectExtensions.cs</code> in the GitHub project <a href="https://github.com/jpmikkers/Baksteen.Extensions.DeepCopy" rel="nofollow noreferrer">jpmikkers/Baksteen.Extensions.DeepCopy</a>. A deep copy operation of a large data structure that previously took us about 30 minutes, now feels almost instantaneous.</p>\n<p>This improved version has the following documentation:</p>\n<blockquote>\n<h2>C# extension method for fast object cloning.</h2>\n<p>This is a speed-optimized fork of Alexey Burtsev\'s deep copier. Depending on your usecase, this will be 2x - 3x faster than the original. It also fixes some bugs which are present in the original code. Compared to the classic binary serialization/deserialization deep clone technique, this version is about seven times faster (the more arrays your objects contain, the bigger the speedup factor).</p>\n<p>The speedup is achieved via the following techniques:</p>\n<ul>\n<li>object reflection results are cached</li>\n<li>don\'t deep copy primitives or immutable structs &amp; classes (e.g. enum and string)</li>\n<li>to improve locality of reference, process the \'fast\' dimensions or multidimensional arrays in the inner loops</li>\n<li>use a compiled lamba expression to call MemberwiseClone</li>\n</ul>\n<h3>How to use:</h3>\n<pre class="lang-cs prettyprint-override"><code>using Baksteen.Extensions.DeepCopy;\n...\nvar myobject = new SomeClass();\n...\nvar myclone = myobject.DeepCopy()!;    // creates a new deep copy of the original object \n</code></pre>\n<p>Note: the exclamation mark (null-forgiving operator) is only required if you enabled nullable referency types in your project</p>\n</blockquote>\n'}]
['https://Stackoverflow.com/questions/78536', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3742/']