deep copying objects in C#

C# — Tags :, , , — admin @ 21:26

One of the fastest ways to deep copy an object is to serialize it to a binary stream and unserialize it to a new object, in that matter:

  1.        /// <summary>
  2.         /// Creates a deep copy of a serializable object
  3.         /// </summary>
  4.         /// <typeparam name="T">Any type</typeparam>
  5.         /// <param name="serializableObject">serializable object</param>
  6.         /// <returns>cloned object</returns>
  7.         public static T CloneOf<T>(T serializableObject)
  8.         {
  9.             object objCopy = null;
  10.             MemoryStream stream = new MemoryStream();
  11.             BinaryFormatter binFormatter = new BinaryFormatter();
  12.             binFormatter.Serialize(stream, serializableObject);
  13.             stream.Position = 0;
  14.             objCopy = (T) binFormatter.Deserialize(stream);
  15.             stream.Close();
  16.             return (T) objCopy;
  17.         }
  18.  
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License.
(c) 2012 Random namespace | powered by WordPress with Barecity