Click here to Skip to main content
15,884,836 members
Articles / Programming Languages / C#

Object Cloning at its simplest

Rate me:
Please Sign up or sign in to vote.
2.55/5 (8 votes)
28 Feb 2008CDDL1 min read 42.7K   342   12  
A reusable static class to clone objects, not specific to TYPE of the object
/*
 * By - Rahul Dantkale
 * Company - Indigo Architects
 * 
 */
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;     
      
/// <summary>
/// This clones any type of object you want to
/// </summary>
public static class ObjectClone
{
    /// <summary>
    /// Perform a Clone of the object asdfas.
    /// </summary>
    /// <typeparam name="T">The type of object being cloned.</typeparam>
    /// <param name="source">The object instance to clone.</param>
    /// <returns>The cloned object.</returns>
    public static T Clone<T>(T RealObject)
    {
        if (!typeof(T).IsSerializable)
            throw new ArgumentException("The type must be marked Serializable", "RealObject");

        // No need to serialize (or clone) null object, simply return null (or the object itself)
        if (Object.ReferenceEquals(RealObject, null))
            return default(T);

        using (Stream objectStream = new MemoryStream())
        {
            IFormatter formatter = new BinaryFormatter();
            formatter.Serialize(objectStream, RealObject);
            objectStream.Seek(0, SeekOrigin.Begin);
            return (T)formatter.Deserialize(objectStream);
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Common Development and Distribution License (CDDL)


Written By
Technical Lead
India India
Acquired Degree of Bachelor in 2007 from Pune University, in VP College Of Engg., Baramati. There on worked in organisations to design and implement web based software applications.

Comments and Discussions