Created
April 13, 2015 23:52
-
-
Save jchandra74/005740e0050b676d1e71 to your computer and use it in GitHub Desktop.
Object Deep Copy via Serialization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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