Cloning

S

Stuart

How to clone objects which contain other objects and collections.

1. In top level class (Class1), write a clone method as follows:

public object Clone()
{
Class1 object=(Class1)this.MemberwiseClone();

//clone objects within this class
object.Object2=(Class2)this.Object2.Clone();

//Also clone any collection objects
object.Collection1=(CollectionClass)this.Collection1.Clone();

return object;
}

2. For the objects within this class (Class1).
a. Inherit the class from Icloneable by adding ": ICloneable" after
class defn.
b. Add clone method
public object Clone()
{
return this.MemberwiseClone();
}

3. For collections within this class (Class1).
a. Inherit the collection from Icloneable by adding ": ICloneable"
after class defn.
b. Add clone method
public object Clone()
{
return new Collection1(this);
}
c. Write a constructor for collection that takes itself as a parameter
public Collection1(ICollection collection)
{
foreach (CollectionClassObject o in collection)
{
this.Add((CollectionClassObject)o.Clone());
}
}
d. Add a clone method to the CollectionClassObject
public object Clone()
{
return this.MemberwiseClone();
}

4. Ensure that all the objects within the top-level class (Class1)
have all their inner objects and collections cloned too. i.e.
Class1.Object1.Object1 is cloned etc.
 
I

Imran Koradia

You can use serialization to perform a deep object clone. Here's an example
(in VB.NET - shouldn't be too hard to convert to C#):

Function CloneObject(ByVal obj As Object) As Object
Dim ms As New System.IO.MemoryStream
Dim bf As New Formatters.Binary.BinaryFormatter(Nothing, New
StreamingContext(StreamingContextStates.Clone))
bf.Serialize(ms, obj)
ms.Seek(0, IO.SeekOrigin.Begin)
Dim oClone As Object = bf.Deserialize(ms)
ms.Close()
Return oClone
End Function

hope that helps..
Imran.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top