Deep clone an object with C#

D

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:

[code]
var serialized = JsonConvert.SerializeObject(original);
var cloned = JsonConvert.DeserializeObject(serialized);
[/code]

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:

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

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

[code]
var cloned = original.Clone();
[/code]

About the author

By Jamie

My Books