DeepCloner.Core 0.1.0

dotnet add package DeepCloner.Core --version 0.1.0                
NuGet\Install-Package DeepCloner.Core -Version 0.1.0                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="DeepCloner.Core" Version="0.1.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add DeepCloner.Core --version 0.1.0                
#r "nuget: DeepCloner.Core, 0.1.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install DeepCloner.Core as a Cake Addin
#addin nuget:?package=DeepCloner.Core&version=0.1.0

// Install DeepCloner.Core as a Cake Tool
#tool nuget:?package=DeepCloner.Core&version=0.1.0                

DeepCloner.Core

Library with extenstion to clone objects for .NET. It can deep or shallow copy objects. In deep cloning all object graph is maintained. Library actively uses code-generation in runtime as result object cloning is blazingly fast. Also, there are some performance tricks to increase cloning speed (see tests below). Objects are copied by its' internal structure, no methods or constructuctors are called for cloning objects. As result, you can copy any object, but we don't recommend to copy objects which are binded to native resources or pointers. It can cause unpredictable results (but object will be cloned).

You don't need to mark objects somehow, like Serializable-attribute, or restrict to specific interface. Absolutely any object can be cloned by this library. And this object doesn't have any ability to determine that he is clone (except with very specific methods).

Also, there is no requirement to specify object type for cloning. Object can be casted to inteface or as an abstract object, you can clone array of ints as abstract Array or IEnumerable, even null can be cloned without any errors.

Installation through Nuget:

Install-Package DeepCloner.Core

This library is a fork of DeepCloner that has been made for the purpose of modernizing DeepCloner and bringing it in line with the rest of the world (.NET Standard 1.3? .NET 4.0? Who can't afford to upgrade from those to a supported standard, really?). It is needed in at least one of my commercial projects.

Supported Frameworks

DeepCloner.Core works for .NET 4.6.2 or higher or for .NET 6.

Usage

Deep cloning any object:

var clone = new { Id = 1, Name = "222" }.DeepClone();

With a reference to same object:

// public class Tree { public Tree ParentTree; }
var t = new Tree();
t.ParentTree = t;
var cloned = t.DeepClone();
Console.WriteLine(cloned.ParentTree == cloned); // True

Or as object:

var date = DateTime.Now;
var obj = (object)date;
obj.DeepClone().GetType(); // DateTime

Shallow cloning (clone only same object, not objects that object relate to)

var clone = new { Id = 1, Name = "222" }.ShallowClone();

Cloning to existing object (can be useful for copying constructors, creating wrappers or for keeping references to same object)

public class Derived : BaseClass
{
    public Derived(BaseClass parent)
    {
        parent.DeepCloneTo(this); // now this has every field from parent
    }
}

Please, note, that DeepCloneTo and ShallowCloneTo requre that object should be class (it is useless for structures) and derived class must be real descendant of parent class (or same type). In another words, this code will not work:

public class Base {}
public class Derived1 : Base {}
public class Derived2 : Base {}

var b = (Base)new Derived1(); // casting derived to parent
var derived2 = new Derived2();
// will compile, but will throw an exception in runtime, Derived1 is not parent for Derived2
b.DeepCloneTo(derived2); 

Details

You can use deep clone of objects for a lot of situations, e.g.:

  • Emulation of external service or deserialization elimination (e.g. in Unit Testing). When code has received object from external source, code can change it (because object for code is own).
  • ReadOnly object replace. Instead of wrapping your object to readonly object, you can clone object and target code can do anything with it without any restriction.
  • Caching. You can cache data locally and want to ensurce that cached object hadn't been changed by other code

You can use shallow clone as fast, light version of deep clone (if your situation allows that). Main difference between deep and shallow clone in code below:

// public class A { public B B; }
// public class B { public int X; }
var b = new B { X = 1 };
var a = new A { B = b };
var deepClone = a.DeepClone();
deepClone.B.X = 2;
Console.WriteLine(a.B.X); // 1
var shallowClone = a.ShallowClone();
shallowClone.B.X = 2;
Console.WriteLine(a.B.X); // 2

So, deep cloning is guarantee that all changes of cloned object does not affect original. Shallow clone does not guarantee this. But it faster, because deep clone of object can copy big graph of related objects and related objects of related objects and related related related objects, and... so on...

This library does not call any method of cloning object: constructors, Equals, GetHashCode, propertes - nothing is called. So, it is impossible for cloning object to receive information about cloning, throw an exception or return invalid data. If you need to call some methods after cloning, you can wrap cloning call to another method which will perform required actions.

Extension methods in library are generic, but it is not require to specifify type for cloning. You can cast your objects to System.Object, or to an interface, add fields will be carefully copied to new object.

Performance tricks

We perform a lot of performance tricks to ensure cloning is really fast. Here is some of them:

  • Using a shallow cloning instead of deep cloning if object is safe for this operation
  • Copying an whole object and updating only required fields
  • Special handling for structs (can be copied without any cloning code, if possible)
  • Cloners caching
  • Optimizations for copying simple objects (reduced number of checks to ensure good performance)
  • Special handling of reference count for simple objects, that is faster than default dictionary
  • Constructors analyzing to select best variant of object construction
  • Direct copying of arrays if possible
  • Custom handling of one-dimensional and two-dimensional zero-based arrays (most of arrays in usual code)

License

MIT license - original fork license also MIT license.

Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Framework net462 is compatible.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETFramework 4.6.2

    • No dependencies.
  • net6.0

    • No dependencies.
  • net7.0

    • No dependencies.
  • net8.0

    • No dependencies.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on DeepCloner.Core:

Package Downloads
Masa.Blazor

Blazor UI component library based on Material Design

Admix.Core

Admix is base framework for building a business application.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
0.1.0 66,160 2/3/2024