Deep clone an object with C#
Published on Jan 25, 2020
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, 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();
Tags: ASP.NET MVC and Web API Tutorial | c# | clone