Click here to Skip to main content
15,881,812 members
Articles / Programming Languages / C#
Article

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.6K   342   12   7
A reusable static class to clone objects, not specific to TYPE of the object

Introduction

This article is about Cloning an object without having to implement ICloneable. And this class can be reused in any (C#) projects because it can clone any object of any TYPE that you specify.

Background

After a huge overnight coding of my project, I suddenly realize, oh! such a big class with so many members. How do I clone it? and I haven't implemented my base class ICloneable. Then I googled and I found all examples showing how to implement ICloneable interface, in codeproject itself I found an article showing the way of using Serialization method. But then this method I had to copy-paste in all the classes. Then I thought of generic(template) class.

Using the code

The first step is to create class. In order to do that, we need to declare the class and create a method as a template/generic definition by adding the generic type parameter <T>

C#
/*
 * By - Rahul Dantkale
 * Company - Indigo Architects
 * 
 */
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;     
      
public static class ObjectClone
{
    public static T Clone<T>(T RealObject)
    {
        using (Stream objectStream = new MemoryStream())
        {
            IFormatter formatter = new BinaryFormatter();
            formatter.Serialize(objectStream, RealObject);
            objectStream.Seek(0, SeekOrigin.Begin);
            return (T)formatter.Deserialize(objectStream);
        }
    }
}        

Note that, the object which can be cloned by this method, the type of that object has to be marked as Serializable like,

C#
[Serializable] 
public class MyClassToClone() 
{
  ...

The reason is, to clone the object I am using Serialization method which serializes memory stream, read the binary data and de-serialize to form object, I typecast it and return the object.

Take a look at source code attached with the article, it's easy to digest.

Points of Interest

This made me to learn Serialization and deserialization using System.Runtime.Serialization and Binary formatter in System.Runtime.Serialization.Formatters.Binary libraries. Using this I am now able to zip in memory to save space. (probably you'll need other libraries to zip and unzip but this article is not about 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

 
GeneralMy vote of 4 Pin
SkyBike5-Oct-10 3:46
SkyBike5-Oct-10 3:46 
GeneralMy vote of 4 Pin
zboulder23-Aug-10 14:37
zboulder23-Aug-10 14:37 
GeneralA better way Pin
HyperteX28-Feb-08 5:09
HyperteX28-Feb-08 5:09 
There is a better Way with an XmlSerializer, because the Class needs no [Serializable] Attribute!
AnswerRe: A better way Pin
Rahul D.28-Feb-08 17:41
Rahul D.28-Feb-08 17:41 
AnswerRe: A better way Pin
ADLER128-Feb-08 21:20
ADLER128-Feb-08 21:20 
GeneralRe: A better way Pin
Robert Rohde28-Feb-08 22:31
Robert Rohde28-Feb-08 22:31 
GeneralRe: A better way Pin
Hristo-Bojilov3-Nov-09 1:04
Hristo-Bojilov3-Nov-09 1:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.