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.

2
  • 2
    possible duplicate of Clone Whole Object Graph Commented Oct 14, 2011 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... Commented Oct 14, 2011 at 13:42

2 Answers 2

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#

Sign up to request clarification or add additional context in comments.

Comments

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))
{
    ...;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.