using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Collections;
using System.Runtime.Serialization;
public static void Main(string[] args)
a.BV.b2Value = "b2Value";
A a2 = new FastDeepCloner(a).Clone<A>();
Console.WriteLine(a2.BV.b2Value + " _ " + a.BV.b2Value);
public class FastDeepCloner
#region Privat Properties
private const BindingFlags Binding = BindingFlags.Instance |
BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy;
private readonly Type _primaryType;
private readonly object _desireObjectToBeCloned;
public FastDeepCloner(object desireObjectToBeCloned)
if (desireObjectToBeCloned == null)
throw new Exception("The desire object to be cloned cant be NULL");
_primaryType = desireObjectToBeCloned.GetType();
_desireObjectToBeCloned = desireObjectToBeCloned;
#region Privat Method Deep Clone
private object DeepClone()
if (_desireObjectToBeCloned == null)
if (_primaryType.IsArray)
return ((Array)_desireObjectToBeCloned).Clone();
object tObject = _desireObjectToBeCloned as IList;
var properties = _primaryType.GetProperties();
var customList = typeof(List<>).MakeGenericType
((properties[properties.Length - 1]).PropertyType);
tObject = (IList)Activator.CreateInstance(customList);
var list = (IList)tObject;
foreach (var item in ((IList)_desireObjectToBeCloned))
var value = new FastDeepCloner(item).DeepClone();
if (_primaryType == typeof(string))
return (_desireObjectToBeCloned as string).Clone();
tObject = FormatterServices.GetUninitializedObject(_primaryType);
var fields = _desireObjectToBeCloned.GetType().GetFields(Binding);
foreach (var property in fields)
var value = property.GetValue(_desireObjectToBeCloned);
if (property.FieldType.IsClass && property.FieldType != typeof(string))
tObject.GetType().GetField(property.Name, Binding).SetValue
(tObject, new FastDeepCloner(value).DeepClone());
tObject.GetType().GetField(property.Name, Binding).SetValue(tObject, value);
#region public Method Clone