Tuesday, August 23, 2011

Best Effort Cloning in C#

private static readonly MethodInfo _method_memberwise_clone = typeof(object).GetMethod("MemberwiseClone", BindingFlags.Instance | BindingFlags.NonPublic);

public static T Clone<T>(T item)
{
    var cloneable = item as ICloneable;
    if (cloneable != null)
    {
        return (T)cloneable.Clone();
    }
    else
    {
        return (T)_method_memberwise_clone.Invoke(item, null);
    }
}

No comments:

Post a Comment