6

How do I create a copy of a class object without any reference? ICloneable makes a copy of a class object (via shallow copy) but doesn't support deep copying. I am looking for a function that is smart enough to read all members of a class object and make a deep copy to another object without specifying member names.

wkl
  • 77,184
  • 16
  • 165
  • 176
Vidya
  • 193
  • 1
  • 2
  • 14
  • 2
    possible duplicate of [Clone Whole Object Graph](http://stackoverflow.com/questions/2417023/clone-whole-object-graph) – xanatos Oct 14 '11 at 13:39
  • 1
    Quick and dirty solution is to serialize the object and immediately deserialize to another object. Of course that depends upon whether the object can be properly serialized... – canon Oct 14 '11 at 13:42

2 Answers2

5

I've seen this as a solution, basically write your own function to do this since what you said about ICloneable not doing a deep copy

public static T DeepCopy(T other)
{
    using (MemoryStream ms = new MemoryStream())
    {
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(ms, other);
        ms.Position = 0;
        return (T)formatter.Deserialize(ms);
    }
}

I'm referencing this thread. copy a class, C#

Community
  • 1
  • 1
jdross
  • 1,188
  • 2
  • 11
  • 30
0
public static object Clone(object obj)
    {
        object new_obj = Activator.CreateInstance(obj.GetType());
        foreach (PropertyInfo pi in obj.GetType().GetProperties())
        {
            if (pi.CanRead && pi.CanWrite && pi.PropertyType.IsSerializable)
            {
                pi.SetValue(new_obj, pi.GetValue(obj, null), null);
            }
        }
        return new_obj;
    }

You can adjust to your needs. For example,

if (pi.CanRead && pi.CanWrite && 
       (pi.PropertyType == typeof(string) || 
        pi.PropertyType == typeof(int) || 
        pi.PropertyType == typeof(bool))
    )
{
    pi.SetValue(new_obj, pi.GetValue(obj, null), null);
}

OR

if (pi.CanRead && pi.CanWrite && 
    (pi.PropertyType.IsEnum || pi.PropertyType.IsArray))
{
    ...;
}
ADM-IT
  • 3,719
  • 1
  • 25
  • 26