Deep clone an object with C# Deep clone an object with C#

Cloning is a common thing I need to do in my C# project. The most common case I use this is with my Entity Framework projects. I first fetch my object using a standard Linq query.

Once I have this object, EF is now tracking any changes to the object. I want a duplicate object of this so I can track a before and after state, so I want to clone the fetched object. To do this I use JSON.Net nuget package.


First be sure you've installed the JSON.Net package. Once installed the following two lines of code will accomplish it:


var serialized = JsonConvert.SerializeObject(original);
var cloned = JsonConvert.DeserializeObject(serialized);

Since I'm a fan of extension methods (as I've demonstrated with converting a date with C#), I've created a class and wrapped this in an extension method:


public static class SystemExtension
{
public static T Clone(this T original)
{
var serialized = JsonConvert.SerializeObject(original);
return JsonConvert.DeserializeObject(serialized);
}
}

I've added this as a SystemExtension which means I can access this extension method on any object by adding .Clone() to it.


var cloned = original.Clone();

Published on Jan 25, 2020

Tags: ASP.NET MVC and Web API Tutorial | c# | clone

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.