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.
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>
public static class ObjectClone
public static T Clone<T>(T RealObject)
using (Stream objectStream = new MemoryStream())
IFormatter formatter = new BinaryFormatter();
Note that, the object which can be cloned by this method, the type of that object has to be marked as Serializable like,
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).