13 July, 2006

Cloning Objects

Quite a while ago I wrote a post about Obvious API’s. To solve that problem I ”Cloned” an XmlDocument object by creating a new and inserting the xml string from the original object. I was not at all satisfied with that solution but with a deadline around the corner and a working solution. Hey what can I say, I left it that way.

XmlDocument xmlDoc =new XmlDocument();
xmlDoc.LoadXml(xmlDocIn.OuterXml);

Just the other day I was fooling around with .Net Framework 2.0 and needed to clone an object that didn’t expose a clone method and that I had not written my self. So after some research on the subject I came up with the following generic object cloner.

public class ObjectCloner
{
    publicdelegateobject CloneDelegate(object o);
    privatestatic CloneDelegate cloner;

    publicstatic T Clone(T o)
    {
        if (cloner == null)
        {
            MethodInfo methodInfo = typeof(object).GetMethod("MemberwiseClone", BindingFlags.Instance | BindingFlags.NonPublic);
						cloner = (CloneDelegate)Delegate.CreateDelegate( typeof(CloneDelegate), null, methodInfo);
        }
        return (T)cloner(o);
    }
}

Seems to work fine, tough I haven’t tested it a lot. So if you try this technic and run into problems, please let me know!


Tags: