Have you ever used the Clone() method of DataSet? This method creates an empty class with same structure as original DataSet.
You can write your own clonable classes. To do so, you must implement IClonable. The following code shows a clonable Test class.
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public Class Test : IClonable
{
public Test()
{
}
// deep copy in separeate memory space
public object Clone()
{
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, this);
ms.Position = 0;
object obj = bf.Deserialize(ms);
ms.Close();
return obj;
}
}
ShyamPosted Mar 19, 2010, 12:18 AM
That was a nice one Surajit. Thanks a lot. But for the use in the Silverlight the following stub works as IClonable is not available. public static T DeepCopy<T>(this T objectToCopy) { T copy; DataContractSerializer serializer = new DataContractSerializer(typeof(T)); using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, objectToCopy); ms.Position = 0; copy = (T)serializer.ReadObject(ms); } return copy; }
AlejandroPosted Jun 18, 2009, 2:18 PM
Cool! thx!
Peter RitchiePosted Feb 11, 2008, 3:41 PM
This only works with classes that are serializable (they have the SerializeableAttribute or implement ISerializeable). Plus, ICloneable is deprecated. See Framework Design Guidelines (http://blogs.msdn.com/brada/archive/2003/04/09/49935.aspx) and Item 27 of Effective C#
Thinathayalan GanesanPosted May 4, 2007, 3:47 PM
Is there a straightforward way to clone a non-serializable class? how can i clone a Datagrid, which is non-serializable, without using reflections?