Here’s a couple of tricks to implementing ICloneable.
First, if your class supports serialization or deserialization, you can serialize the object you wish to clone and deserialize it to a new object. This has a couple of obvious drawbacks:
- If you’ve marked fields or properties to be ignored by serialization, you won’t see them in the clone.
- If you’ve implemented IXmlSerializable to make custom serialization, you’ll lose values that are not in the XML.
Another trick that I’ve come up with is to use Reflection to clone:
public static object CloneThroughReflection(object source)
{
Type ObjectType = source.GetType();
// Create a new object of the same type as the source and call its default constructor
object MyClone = System.Activator.CreateInstance(ObjectType, null);
// Loop through the fields
FieldInfo[] FieldInformation = ObjectType.GetFields();
for (int i = 0; i < FieldInformation.Length; i++)
{
// Set the clone's field to the same value as the source's
FieldInfo MyField = FieldInformation[i];
object SourceValue = MyField.GetValue(source);
MyField.SetValue(MyClone, SourceValue);
}
return MyClone;
}
This function is more accurate at making a deep clone of an object, as it doesn’t rely on a field’s or property’s inclusion in the XML to appear in the clone.
