Skip to content

Instantly share code, notes, and snippets.

@cameronism
Created December 10, 2014 00:24
Show Gist options
  • Select an option

  • Save cameronism/90df247375dfd79e98d2 to your computer and use it in GitHub Desktop.

Select an option

Save cameronism/90df247375dfd79e98d2 to your computer and use it in GitHub Desktop.
Slow .NET Object Cloner
public static class SlowCloner
{
public static T Clone<T>(T val, int depth = 64)
{
return (T)CloneNonGeneric(val, typeof(T), depth);
}
static object CloneNonGeneric(object val, Type type, int depth = 64)
{
if (val == null) return null;
switch (Type.GetTypeCode(type))
{
case TypeCode.Object:
return CloneObject(val, type, depth);
default:
// all the other typecodes are immutable anyway
return val;
}
}
static object CloneObject(object val, Type type, int depth)
{
var fields = type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
var clone = FormatterServices.GetUninitializedObject(type);
foreach (var fi in fields)
{
fi.SetValue(clone, CloneNonGeneric(fi.GetValue(val), fi.FieldType, depth - 1));
}
return clone;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment