afaolek afaolek - 4 days ago 6
C# Question

Creating a copy of an object in C#


Possible Duplicate:

How do you do a deep copy an object in .Net (C# specifically)?




Please have a look at the code below (excerpt from a C# book):

namespace Example
{
class MyClass
{
public int val;
}
struct myStruct
{
public int val;
}
class Program
{
static void Main(string[] args)
{
MyClass objectA = new MyClass();
MyClass objectB = objectA;
objectA.val = 10;
objectB.val = 20;
myStruct structA = new myStruct();
myStruct structB = structA;
structA.val = 30;
structB.val = 40;
Console.WriteLine("objectA.val = {0}", objectA.val);
Console.WriteLine("objectB.val = {0}", objectB.val);
Console.WriteLine("structA.val = {0}", structA.val);
Console.WriteLine("structB.val = {0}", structB.val);
Console.ReadKey();
}
}
}


I understands it produces the output below

objectA.val = 20
objectA.val = 20
structB.val = 30
structB.val = 40


The last two lines of the output I have no problem with, but the first two tell me that
objectA
and
objectB
are pointing to the same memory block (since in C#, objects are reference types).

The question is how do make
objectB
, a copy of
objectA
so that it points to a different area in memory. I understand that trying to assign their members may not work since those members may be references, too. So how do I go about making
objectB
a completely different entity from
objectA
?

Thanks

Answer

There is no built-in way. You can have MyClass implement the IClonable interface (but it is sort of deprecated) or just write your own Copy/Clone method. In either case you will have to write some code.

For big objects you could consider Serialization + Deserialization (through a MemoryStream), just to reuse existing code.

Whatever the method, think carefully about what "a copy" means exactly. How deep should it go, are there Id fields to be excepted etc.

Comments