Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create copy of class object without any reference?

Tags:

c#

asp.net

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.

like image 975
Vidya Avatar asked Oct 09 '22 18:10

Vidya


1 Answers

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#

like image 154
jdross Avatar answered Oct 13 '22 11:10

jdross