How to Deep Clone an Object in C#?

Some time ago I ran into a problem that I need to make a complete copy of the C# object. Before I show you how to deep-copy an object. I want to briefly describe how variables are arranged in .NET. In C#, when we create an object, it is stored in memory with a specific memory address. If we create another variable and assign it the same object, both variables will reference the same memory location. Any changes made to the object through one variable will be reflected in the other variable as well. This is known as shallow copying. And deep copying involves creating a new copy of the object with its own memory address, and changes made to one copy won’t affect the other copy. This is important in scenarios where we want to make changes to the object without affecting the original object.

Steps to Deep Clone an Object in C# using Serialization

To perform deep cloning using serialization, we will serialize the original object into a JSON string and then deserialize it to create a new object with its own memory address. This will create a complete copy of the original object with all its values and properties.

My steps are:

  1. Install Newtonsoft.Json nuget package
  2. Create a generic method to clone objects using JSON serialization

Clone method:

public static class ObjectExtensions
{
    public static T? CloneJson<T>(this T source)
    {
        if (ReferenceEquals(source, null)) return default;
        var deserializeSettings = new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace };
        return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source), deserializeSettings);
    }
}

This extension method adds a CloneJson method to all objects. The purpose of this method is to create a deep copy of an object by serializing it to JSON, and then deserializing it back into a new object.

The ObjectCreationHandling.Replace setting ensures that the deserialization process creates new instances of objects instead of reusing existing instances.

The JsonConvert class serializes the source object to JSON using JsonConvert.SerializeObject(source), and then immediately deserialize the JSON back into a new object of type T using JsonConvert.DeserializeObject<T>(...).

Example – Deep Clone Class

C# Deep Clone Class JSON Serialization

There are other ways to clone objects, for example, with the implementation of the ICloneable interface. In this article, I showed how to make a copy of an object using JSON serialization.

You may also be interested to read my next articles:

Leave a Comment