Clone deep objects in C#: simple and effective – Programming, Pseudocode Example, C# Programming Example
C#

Clone deep objects in C#: simple and effective

In this article, I will explain how to successfully clone C # objects in depth in a simple and above all effective way.

The idea is to write code that will clone objects even if classes evolve.

What is the cloning of objects?

Cloning objects simply means creating a new instance and copying all the properties of a “source” object. If the “source” object contains sub-objects, it must also be copied (in depth).

Here is an example if we had to do it “by hand”:

You will understand the principle.
This method is simple but it has a big problem: each time the Command or User classes evolve, it is necessary to update the code that performs the cloning. This type of behavior does not respect the OCP principle and will therefore increase maintenance.

The practical solution to use

To correct this, I propose a simple trick for cloning serializable objects (you will have to add the [Serializable] attribute on your classes).

It uses the serialization / deserialization mechanisms to build a new copied object.

Here is the code of the copy method:

Then, to use it, just call the method like this:

This technique is very powerful and easy to implement. It also allows you to clone without the need to write the code to copy each property. Moreover, it makes it possible to adapt automatically to changes in class (OCP principle).

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.