I had the need to clone objects to do original vs modified delta checks. I decided that I could either do a lot of work to make copies or go the easy route. As always, smarter over harder prevailed.
Here is a simple extension class to put into your infrastructure. Enjoy!
using System;
using System.IO;
using System.Xml.Serialization;
namespace Seekford.Extensions
{
public static class ObjectCopyMachine
{
/// <summary>
/// Extension to perform a deep Copy of the object specified.
/// </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>(this 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 (Object.ReferenceEquals(source, null))
{
return default(T);
}
XmlSerializer serializer = new XmlSerializer(source.GetType());
Stream stream = new MemoryStream();
using (stream)
{
serializer.Serialize(stream, source);
stream.Seek(0, SeekOrigin.Begin);
return (T)serializer.Deserialize(stream);
}
}
}
}
Now you can just call any object and say. Abracadabra…… myObject.Clone();
Happy Coding!
#1 by Tejas Patel on October 31, 2011 - 8:54 am
I am getting error like XMLInclude is required.