Hi,
There is no built in copy function in .NET objects. There we have a object.Clone() method that creates another object with the same properties and state of the original one, but if the original class has some reference to other typed objects
the object.Clone() method does not create new sub objects for the new clone. It just passes references to the new clone. If what Lasse tells do not work try this..
If you have a base class everything is easy but you should add some
code to all of your inherited classes;
1. Add the code below to your base class:
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
2. Add attribute to base and all of your inherited classes:
[Serializable]
public class MyBase
{...}
[Serializable]
public class MyChildClass01
{...}
[Serializable]
public class MyChildClass02
{...}
3.In your base class add the function below:
[Serializable]
public class MyBase
{
....
public MyBase GetACopy()
{
MyBase retval = null;
IFormatter formatter = new BinaryFormatter();
Stream stream = new System.IO.MemoryStream();
formatter.Serialize(stream, this);
stream.Seek(0,System.IO.SeekOrigin.Begin);
retval = ((MyBase)(formatter.Deserialize(stream)));
return retval;
}
}
4. Use the GetACopy() function by casting
public class UserClass
{
public void SampleMethod()
{
//Create Original
MyChildClass01 chOriginal = new MyChildClass01();
//Set Properties of Original Class
chOriginal.Name = "Original" ... etc.
//Create A Copy
MyChildClass01 chCopy = (MyChildClass01) (chOriginal.GetACopy());
}
}
5. You should write property accessors for all the variables in your
inherited class to be copied exactly.
6. Only the serializable sub classes will be copied; this may be a
DataSet for instance; it implements ISerializable interface
Good Luck,