Friday 6 February 2015

How to Deep Clone an Object by Value and not by Reference in C#


The following code snippet using serialization to deep clone an object in C#. Please note: ICloneable is a deprecated API. ICloneable is considered a poor API, since it does not specify whether the result is a deep or a shallow copy.

Code Snippet
  1. // Usage
  2. CLASSNAME clonedInstance = DeepClone<CLASSNAME>(instance);
  3.  
  4.  
  5. // Deep clones an object
  6. // Your class (and all sub-classes) MUST be marked as [Serializable] in order for this to work.
  7. public static T DeepClone<T>(T obj)
  8. {
  9.     using (var ms = new System.IO.MemoryStream())
  10.     {
  11.         var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
  12.         formatter.Serialize(ms, obj);
  13.         ms.Position = 0;
  14.  
  15.         return (T)formatter.Deserialize(ms);
  16.     }
  17. }
End of Code Snippet

1 comment:

Pierre said...

Hello nice bblog