Alex Rivera | Logout

How can I copy an instance of a class in C#

Asked 2009-06-23T07:02:53.277
29

Is there a way to copy an object in C#? Something like:

var dupe = MyClass(original);

I want them to be equal such that all data members are identical, but not share the same memory location.

Edit
Report

1 Answer

2

An easy way to clone an object is writing it into a stream and read it again:

public object Clone()
{
    object clonedObject = null;
    BinaryFormatter formatter = new BinaryFormatter();
    using (Stream stream = new MemoryStream())
    {
        formatter.Serialize(stream, this);
        stream.Seek(0, SeekOrigin.Begin);
        clonedObject = formatter.Deserialize(stream);
    }

    return clonedObject;
}

But be aware of, that this can cause problems with so called aggregate object.

answered 2009-06-23T07:36:57.187

Your Answer