Quickly Clone a Serializable Object in C#

Here’s a quick way to get a clone of your serializable object in C#:

 
public static object GetClone(object cloneThis)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms= new MemoryStream();
bf.Serialize(ms, cloneThis);
ms.Flush();
ms.Position = 0;
return bf.Deserialize(ms);
}
This entry was posted in C#. Bookmark the permalink.

5 Responses to Quickly Clone a Serializable Object in C#

  1. Rahul Dantkale says:

    Nice trick to Clone… this reduced my manual clone method from 100s of lines to 6..

    Gud one

  2. galaktor^ says:

    Nice. I suggest adding a check to the method:

    if( !cloneThis.GetType().IsSerializable )
    {
    throw new ArgumentException( “Object must be serializable.”);
    }

  3. greg says:

    Great idea – thanks galaktor

  4. auser says:

    I really liked your method. thanks for sharing this:) hope many people will find it useful as I did. have read lots of articles on the topic, but have never thought that could be so easy

  5. Sophi says:

    Is it deep clone?

Leave a Reply

Your email address will not be published. Required fields are marked *