ICloneable tricks & shortcuts

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.

Advertisements

2 thoughts on “ICloneable tricks & shortcuts

  1. Dan, that’s correct. I’m using Activator.CreateInstance(Type, Object[]) to make the cloned object, and passing null as the Object[] tells it to use the default constructor. It wouldn’t necessarily have to be public, just visible to the CloneThroughReflection() method. So if you had:

    public class MyClass
    {
    private MyClass()
    {

    }
    public MyClass CloneThroughReflection()
    {

    }
    }

    that would work.

    Also, I should really modify it to see if MyField’s value’s type supports ICloneable and use that rather than just SourceValue = MyField.GetValue(source), but I’ve not done so yet. 😉

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s