Introduction
I was looking around on The Code Project and saw an article talking about the different implementation styles for deep cloning an object. The article referred to an article using Reflection for Deep Cloning an object, but had no article to reference for using Serialization.
Using the Code
This is a helper class that can be used to perform a deep copy of an object:
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
public static class ObjectCopier
{
public static T Clone<T>(T source)
{
if (!typeof(T).IsSerializable)
{
throw new ArgumentException("The type must be serializable.", "source");
}
if (Object.ReferenceEquals(source, null))
{
return default(T);
}
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
using (stream)
{
formatter.Serialize(stream, source);
stream.Seek(0, SeekOrigin.Begin);
return (T)formatter.Deserialize(stream);
}
}
}
Usage of this class becomes ObjectCopier.Clone(objectBeingCloned);
.
Points of Interest
In case you prefer to use the new Extension methods of C# 3.0, change the method to have the following signature:
public static T Clone<T>(this T source)
{
...
}
Now the method call simply becomes objectBeingCloned.Clone();
.
History
- 22nd February, 2008: Version 1.0: Initial release
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.