SoFunction
Updated on 2025-03-06

Introduction to 4 deep copy methods in C#

1: Using reflection to achieve

public static T DeepCopy<T>(T obj)
{
  //If it is a string or value type, it will be returned directly  if (obj is string || ().IsValueType) return obj;

  object retval = (());
  FieldInfo[] fields = ().GetFields( |  |  | );
  foreach (FieldInfo field in fields)
  {
    try { (retval, DeepCopy((obj))); }
    catch { }
  }
  return (T)retval;
}

2: Use xml serialization and deserialization to implement

public T DeepCopy<T>(T obj)
    {
      object retval;
      using (MemoryStream ms = new MemoryStream())
      {
        XmlSerializer xml = new XmlSerializer(typeof(T));
        (ms, obj);
        (0, );
        retval = (ms);
        ();
      }
      return (T)retval;
    }

3: Implementation using binary serialization and deserialization

public static T DeepCopy&lt;T&gt;(T obj)
{
  object retval;
  using (MemoryStream ms = new MemoryStream())
  {
    BinaryFormatter bf = new BinaryFormatter();
    //Serialize to stream    (ms, obj);
    (0, );
    //Deserialize to object    retval = (ms);
    ();
  }
  return (T)retval;
}

4: Use silverlight DataContractSerializer to implement it for use in silverlight client

public static T DeepCopy<T>(T obj)
    {
      object retval;
      using (MemoryStream ms = new MemoryStream())
      {
        DataContractSerializer ser = new DataContractSerializer(typeof(T));
        (ms, obj);
        (0, );
        retval = (ms);
        ();
      }
      return (T)retval;

Added: The first one has implemented a deep copy through recursion.