How to deep clone object in .net using NetClone

Cloning a complex object is not an easy task. Especially if you need to preserve some object properties references within the object graph. Plus, this is exactly the kind of boring codes you don’t want to be writing , anyway. 😉

I’ve created a library called NetClone, that you can use to configure the clone graph for your object. The object cloner instance keep tracks of which object references must be preserved vs recursively cloned and rely on JSON serialization to duplicate objects.

To get started simply open your Package manager console :

Install-Package Newsoft.Netclone

Here are some example of how to use the library

Example : Deep clone an entire objects with minimal configuration

            var a = Helper.InitTestObject();
            var clone = new Newsoft.NetClone.ObjectCloner<A>();
            var aprime = clone.Clone(a);

            a.B.F1 = 12345;
            aprime.B.F1 = 6789;

            Assert.AreNotEqual(a.B.F1, aprime.B.F1);

Simple clone for class A where member B will be cloned and it’s member C reference will be preserved after clone.

            var clone = new ObjectCloner<A>();
            clone.ForMember(V => V.B).CloneMode(CloneMode.Copy);
            clone.ForMember(V => V.B.C).CloneMode(CloneMode.Reference);

It has support for collections

            var clone = new ObjectCloner<A>();
            clone.ForMember(V => V.Bs.Select(V1=>V1.B).CloneMode(CloneMode.Copy);

It uses Newtonsoft JSON Serializer to copy the objects.

Library also has capability to configure clone on non-generic fluent configuration.

Clone a collection member

            var clone = new ObjectCloner();
            var a = Helper.InitTestObject();
            clone.ForMember("Bs[*].C").CloneMode(CloneMode.Copy);

Set member of a collection to preserve reference

            var clone = new ObjectCloner();
            clone.ForMember("Bs[*]").CloneMode(CloneMode.Copy);
            clone.ForMember("Bs[*].C").CloneMode(CloneMode.AsReference);

 

Github :  https://github.com/newsoftinc/NetClone or simply install from nuget package

Trackbacks/Pingbacks

  1. Welcome back! It’s the #Friday Five – Microsoft MVP Award Program Blog - […] How to deep clone object in .net using NetClone […]

Submit a Comment

Your email address will not be published. Required fields are marked *

Share This