c# - Deep cloning objects -


i want like:

myobject myobj = getmyobj(); // create , fill new object myobject newobj = myobj.clone(); 

and make changes new object not reflected in original object.

i don't need functionality, when it's been necessary, i've resorted creating new object , copying each property individually, leaves me feeling there better or more elegant way of handling situation.

how can clone or deep copy object cloned object can modified without changes being reflected in original object?

whilst standard practice implement icloneable interface (described here, won't regurgitate), here's nice deep clone object copier found on the code project while ago , incorporated in our stuff.

as mentioned elsewhere, require objects serializable.

using system; using system.io; using system.runtime.serialization; using system.runtime.serialization.formatters.binary;  /// <summary> /// reference article http://www.codeproject.com/kb/tips/serializedobjectcloner.aspx /// provides method performing deep copy of object. /// binary serialization used perform copy. /// </summary> public static class objectcopier {     /// <summary>     /// perform deep copy of object.     /// </summary>     /// <typeparam name="t">the type of object being copied.</typeparam>     /// <param name="source">the object instance copy.</param>     /// <returns>the copied object.</returns>     public static t clone<t>(t source)     {         if (!typeof(t).isserializable)         {             throw new argumentexception("the type must serializable.", "source");         }          // don't serialize null object, return default object         if (object.referenceequals(source, null))         {             return default(t);         }          iformatter formatter = new binaryformatter();         stream stream = new memorystream();         using (stream)         {             formatter.serialize(stream, source);             stream.seek(0, seekorigin.begin);             return (t)formatter.deserialize(stream);         }     } } 

the idea serializes object , deserializes fresh object. benefit don't have concern cloning when object gets complex.

and use of extension methods (also referenced source):

in case prefer use new extension methods of c# 3.0, change method have following signature:

public static t clone<t>(this t source) {    //... } 

now method call becomes objectbeingcloned.clone();.

edit (january 10 2015) thought i'd revisit this, mention started using (newtonsoft) json this, should be lighter, , avoids overhead of [serializable] tags. (nb @atconway has pointed out in comments private members not cloned using json method)

/// <summary> /// perform deep copy of object, using json serialisation method. note: private members not cloned using method. /// </summary> /// <typeparam name="t">the type of object being copied.</typeparam> /// <param name="source">the object instance copy.</param> /// <returns>the copied object.</returns> public static t clonejson<t>(this t source) {                 // don't serialize null object, return default object     if (object.referenceequals(source, null))     {         return default(t);     }      // initialize inner objects individually     // example in default constructor list property initialized values,     // in 'source' these items cleaned -     // without objectcreationhandling.replace default constructor values added result     var deserializesettings = new jsonserializersettings {objectcreationhandling = objectcreationhandling.replace};      return jsonconvert.deserializeobject<t>(jsonconvert.serializeobject(source), deserializesettings); } 

Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -