Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Object Deep Copy via Serialization
namespace __NAMESPACE__
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public static class ObjectCopier
/// <summary>
/// Perform a deep copy of the object.
/// </summary>
/// <typeparam name="T">The type of object being copied.</typeparam>
/// <param name="source">The object instance to copy.</param>
/// <returns>The copied object.</returns>
public static T Clone<T>(T source)
if (!typeof (T).IsSerializable)
throw new ArgumentException("The type must be serializable.", "source");
// Don't serialize a null object, simply return the default for that object
if (ReferenceEquals(source, null))
return default(T);
var formatter = new BinaryFormatter();
var stream = new MemoryStream();
using (stream)
formatter.Serialize(stream, source);
stream.Seek(0, SeekOrigin.Begin);
return (T) formatter.Deserialize(stream);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.