Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net Deep cloning - what is the best way to do that?

Tags:

c#

.net

clone

I need to perform deep cloning on my complex object model. What do you think is the best way to do that in .Net?
I thought about serializing / Deserializing
no need to mention that MemberwiseClone is not good enough.

like image 316
Adi Barda Avatar asked Aug 09 '09 12:08

Adi Barda


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.

What is deep clone in C#?

Deep Copy: It is a process of creating a new object and then copying the fields of the current object to the newly created object to make a complete copy of the internal reference types. If the specified field is a value type, then a bit-by-bit copy of the field will be performed.

What is the most efficient way to deep clone an object in Javascript?

According to the benchmark test, the fastest way to deep clone an object in javascript is to use lodash deep clone function since Object. assign supports only shallow copy.

How do you clone in C#?

C# | Clone() Method It is used to clone the string object, which returns another copy of that data. In other words, it returns a reference to this instance of String. The return value will be only another view of the same data. Clone method called directly on current String instance.


1 Answers

If you control the object model, then you can write code to do it, but it is a lot of maintenance. There are lots of problems, though, which mean that unless you need absolutely the fastest performance, then serialization is often the most manageable answer.

This is one of the cases where BinaryFormatter works acceptably; normally I'm not a fan (due to the issues with versioning etc) - but since the serialized data is for immediate consumption this isn't an issue.

If you want it a bit faster (but without your own code), then protobuf-net may help, but requires code changes (to add the necessary metadata etc). And it is tree-based (not graph-based).

Other serializers (XmlSerializer, DataContractSerializer) are also fine, but if it is just for clone, they may not offer much over BinaryFormatter (except perhaps that XmlSerializer doesn't need [Serializable].

So really, it depends on your exact classes and the scenario.

like image 183
Marc Gravell Avatar answered Nov 06 '22 04:11

Marc Gravell