tags:

views:

115

answers:

4

I have an object created in c# say Object1. I need to temporarily back up this object to another object say ObjectOriginal.

However if I do ObjectOriginal = Object1, any changes to Object 1 affect ObjectOriginal. How do I go about this?

+1  A: 

take a look at http://stackoverflow.com/questions/78536/cloning-objects-in-c

rerun
+1  A: 

Either implement Clone() on your class or use Object.MemberwiseClone()

http://msdn.microsoft.com/de-de/library/system.object.memberwiseclone(VS.80).aspx

Arthur
+2  A: 

It all depends on what Object1 actually is, i.e. is it a DataTable, a String, or something else entirely?

By writing:

object Object1 = new Thing();
object Object2 = Object1;

You get a second reference to the object you instantiated in the first line. What you need to do is look at "Thing" and see if it has a Copy, Clone or similarly named method and use that:

object Object1 = new Thing();
object Object2 = Object1.Copy();

For example, DataTable offers both Copy and Clone methods, where Copy duplicates both the structure of the DataTable and the data and Clone only duplicates the structure.

Rob
A: 

If you want a copy of an object the question is always: How deep will the copy occur? What should happen to the objects within my object. Should these be copied also and if yes what should happen to their references??

For more informations take at starting point this blog post from Brad Abrams.

Oliver