Blog Stats
  • Posts - 94
  • Articles - 0
  • Comments - 10
  • Trackbacks - 0

 

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);
}


Feedback

# re: Quickly Clone a Serializable Object in C#

Gravatar Nice trick to Clone... this reduced my manual clone method from 100s of lines to 6.. <br /><br />Gud one 1/30/2008 7:38 AM | Rahul Dantkale

# re: Quickly Clone a Serializable Object in C#

Gravatar Nice. I suggest adding a check to the method:

if( !cloneThis.GetType().IsSerializable )
{
throw new ArgumentException( "Object must be serializable.");
} 8/20/2009 12:22 PM | galaktor^

# re: Quickly Clone a Serializable Object in C#

Gravatar Great idea - thanks galaktor 8/20/2009 10:37 PM | greg

# re: Quickly Clone a Serializable Object in C#

Gravatar 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 1/11/2010 6:14 AM | Rapid Share

# re: Is it deep clone?

Gravatar Is it deep clone? 1/23/2010 3:10 PM | Sophi

Post a comment





 

Please add 8 and 6 and type the answer here:

 

 

Copyright © Greg Steen