How to Deep Copy properly?

  • Thread starter Thread starter Jax
  • Start date Start date
J

Jax

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
 
Jax said:
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?

You copied the references.
See below:
class CopyExample
{
string str;
public object ShallowCopy()
{
CopyExample ce = new CopyExample();
ce.str = this.str;
return (object)CopyExample;
}
public object DeepCopy()
{
CopyExample ce = new CopyExample();
ce.str = this.str.Clone();
retunr (object)CopyExample;
}
}
 
Hello

For the String type in particular, Clone method returns a reference to the
string itself, this is because strings in .NET are immutable

Best regards
Sherif
 
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
 
Back
Top