Submitted by Thomas on Sat, 2006-10-14 09:38.
Here is a C# class that can create a deep copy clone of an arbitrary object. The thing that's special about it is that it should work for any class that extends it, so that you don't need to re-write a custom clone() function for every child class (as it seems the C# framework creators would like). This does a deep copy so be careful about members that recursively include one another.
Another way of doing this would be to use serialization . . . I just personally thought the reflection package would be more elegant.
/// Class for data which can be cloned.
public class THData
/// Function for doing a deep clone of an object.
/// Returns a deep-copy clone of the object.
public virtual THData DeepClone()
//First do a shallow copy.
THData returnData = (THData)this.MemberwiseClone();
//Get the type.
Type type = returnData.GetType();
//Now get all the member variables.
FieldInfo fieldInfoArray = type.GetFields();
//Deepclone members that extend THData.
//This will ensure we get everything we need.
foreach (FieldInfo fieldInfo in fieldInfoArray)
//This gets the actual object in that field.
object sourceFieldValue = fieldInfo.GetValue(this);
//See if this member is THData
if (sourceFieldValue is THData)
//If so, cast as a THData.
THData sourceTHData = (THData)sourceFieldValue;
//Create a clone of it.
THData clonedTHData = sourceTHData.DeepClone();
//Within the cloned containig class.