Cloning Objects

12/12/2005 2:17:49 PM

Cloning Objects

There’s been a few times when I wanted to clone an object, but the object did not provide a clone method, but I knew that such an operation would be safe. One class are enumerator objects returned by non-destructive iterators. While enumerating a stream of values, it is often useful to record the state of the enumeration at an arbitrary point and then later restart the enumeration again from that point.

Here’s a very fast function that I came up with for cloning any object.

public delegate object CloneDelegate(object o);

private static CloneDelegate cloner;
public static T Clone<T>(T o)
    if (cloner == null)
        MethodInfo info =
            BindingFlags.Instance | BindingFlags.NonPublic);

        cloner = (CloneDelegate)
typeof(CloneDelegate), null, info);

        Debug.Assert(cloner !=

    return (T) cloner(o);

There are two interesting points in this approach.

  1. We create a typed delegate from a MethodInfo of a protected member to be able to access a normally inaccessible member function and also to avoid the cost of reflection.
  2. We pass in null as the target of the delegate. This turns an instance method into a static method with an extra parameter for this pointer. This is a trick that you won’t find in the MSDN documentation.







Net Undocumented is a blog about the internals of .NET including Xamarin implementations. Other topics include managed and web languages (C#, C++, Javascript), computer science theory, software engineering and software entrepreneurship.

Social Media