deep copying objects in C#
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:
-
/// <summary>
-
/// Creates a deep copy of a serializable object
-
/// </summary>
-
/// <typeparam name="T">Any type</typeparam>
-
/// <param name="serializableObject">serializable object</param>
-
/// <returns>cloned object</returns>
-
public static T CloneOf<T>(T serializableObject)
-
{
-
object objCopy = null;
-
MemoryStream stream = new MemoryStream();
-
BinaryFormatter binFormatter = new BinaryFormatter();
-
binFormatter.Serialize(stream, serializableObject);
-
stream.Position = 0;
-
objCopy = (T) binFormatter.Deserialize(stream);
-
stream.Close();
-
return (T) objCopy;
-
}
-