Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deep clone interconnected objects in C#?

Tags:

c#

clone

What is the best way to deep clone an interconnected set of objects? Example:

class A {
    B theB; // optional
    // ...
}

class B {
    A theA; // optional
    // ...
}

class Container {
    A[] a;
    B[] b;
}

The obvious thing to do is walk the objects and deep clone everything as I come to it. This creates a problem however -- if I clone an A that contains a B, and that B is also in the Container, that B will be cloned twice after I clone the Container.

The next logical step is to create a Dictionary and look up every object before I clone it. This seems like it could be a slow and ungraceful solution, however.

Any thoughts?

like image 227
zildjohn01 Avatar asked Mar 25 '09 21:03

zildjohn01


People also ask

How can you actually the deep cloning of an object?

To achieve a deep copy, we can serialize an object and then deserialize it to a new object.

How do I copy one object to another in C#?

In general, when we try to copy one object to another object, both the objects will share the same memory address. Normally, we use assignment operator, = , to copy the reference, not the object except when there is value type field. This operator will always copy the reference, not the actual object.

Can we achieve deep cloning of an object by serialization?

So similar to the above cloning approaches, we can achieve deep cloning functionality using object serialization and deserialization as well, and with this approach, we do not have worry about or write code for deep cloning — we get it by default.


2 Answers

Its not an elegant solution for sure, but it isn't uncommon to use a dictionary (or hashmap). One of the benefits is that a hashmap has a constant lookup time, so speed does not really suffer here.

like image 110
JoshJordan Avatar answered Sep 24 '22 18:09

JoshJordan


Not that I am familiar with C#, but typically any type of crawling of a graph for some sort of processing will require a lookup table to stop processing an object due to cyclic references. So I would think you will need to do the same here.

like image 32
Robin Avatar answered Sep 23 '22 18:09

Robin