| re: How to Deep Copy properly?
Hello
An easy way to clone an object, is to serialize it to a memory stream, then
unserialize it again.
But this can be done only when the class has [Serializable] attribute
defined, and all fields in the class whether custom or not must have the
serializable attribute.
[Serializable]
public class Class1
{
}
[Serializable]
public class MyClass : ICloneable
{
// all these fields are serializable
int a;
string b;
double c;
decimal[] d;
Class1 e;
// This field is not serializable so we define the NonSerialized
Attribute
[NonSerialized]
TextBox t;
public object Clone()
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, bf);
ms.Position = 0;
return bf.Deserialize(ms);
}
}
Best regards,
Sherif
"Jax" <anonymous@discussions.microsoft.com> wrote in message
news:009c01c3bffd$d1972300$a101280a@phx.gbl...[color=blue]
> I have inherited the ICloneable interface and have set up
> a public object Clone() method;
> This method creates a new version of itself puts all it's
> stuff in it(and yes all custom objects within have the
> same method) then casts that into and object and passes it
> back.
>
> Is this not a deep copy?
> It isn't working, I change the value and it satays changes
> on the originals, how do I sort this out?
>
> Many thanks to any help given.
>
> jax[/color] |