I recently discovered that MemberwiseCloning a class doesn't seem to clone it's subclasses (classes defined within it). They still seem to be treated as pointers. Is there some way I can clone a whole class with all subclasses?
Asked
Active
Viewed 2,655 times
0
-
2" Is there some way I can clone a whole class with all subclasses?" - Yes. Write a clone Method. Search the internet to find the short code snippet that uses serialization. Maybe try typing your title into a serach engine? – Mitch Wheat Jul 28 '13 at 01:40
-
1There is a holo tickbox next to each answer, it gives you a couple of points by ticking it and saves everyone's time by letting them know your question is solved. Good luck:) – Jeremy Thompson Jul 28 '13 at 01:45
1 Answers
2
Use something like this
public object Clone()
{
using (var memStream = new MemoryStream())
{
var binaryFormatter = new BinaryFormatter(
null,
new StreamingContext(StreamingContextStates.Clone));
binaryFormatter.Serialize(memStream, this);
memStream.Seek(0, SeekOrigin.Begin);
return binaryFormatter.Deserialize(memStream);
}
}

Claudio Redi
- 67,454
- 15
- 130
- 155
-
What about performance ?! Should we use this trick or defining the function ICloeable.Clone() for each sub class to gain performance ? – K4timini Jul 24 '14 at 09:00
-
@K4timini: if you need a deep clone, I think this is the most performant method. – Claudio Redi Jul 24 '14 at 12:11