Skip to content

Latest commit

 

History

367 Commits

Folders and files

Repository files navigation

FastCloner

FastCloner

The fastest and most reliable .NET deep cloning library.

FastCloner FastCloner License:MIT

FastCloner is a zero-dependency deep cloning library for .NET, from .NET 4.6 to .NET 10+. It combines source generation with optimized reflection fallback, so deep cloning just works.

✨ Features

  • The Fastest - Benchmarked to beat all other libraries with third-party independent benchmarks verifying the performance. 300x speed-up vs Newtonsoft.Json and 160x vs System.Text.Json
  • The Most Correct - Built for the cases clone libraries get wrong: polymorphism, circular/shared references, readonly and immutable members, deep graphs, delegates, events, collections... Backed by 1,000+ tests, with documented limitations
  • Hybrid AOT - Uses generated clone code wherever possible, with targeted fallback to the runtime engine only where safety or correctness requires it
  • Automatic type discovery - The generator follows usages of generic and abstract types and emits concrete clone paths automatically
  • Embeddable - No dependencies outside the standard library. Source generator and reflection parts can be installed independently
  • Precise control - Override clone behavior per type or member with Clone, Reference, Shallow, or Ignore, at compile time or runtime
  • Selective tracking - FastCloner avoids identity and cycle-tracking overhead by default, but enables it when graph shape or [FastClonerPreserveIdentity] requires it
  • Easy Integration - FastDeepClone() for AOT cloning, DeepClone() for reflection cloning. FastCloner respects standard .NET attributes like [NonSerialized], so you can adopt it without depending on library-specific annotations
  • Production Ready - Used by projects like Foundatio, Jobbr, TarkovSP, SnapX, and WinPaletter, with over 1M downloads on NuGet

Getting Started

Install the package via NuGet:

dotnet add package FastCloner # Reflection
dotnet add package FastCloner.SourceGenerator # AOT

Clone via Reflection

using FastCloner.Code;
var clone = FastCloner.FastCloner.DeepClone(new { Hello = "world", MyList = new List<int> { 1 } });

For convenience, add the following method to your project. We intentionally don't ship this extension to make switching from/to FastCloner easier:

[return: NotNullIfNotNull(nameof(obj))]
public static T? DeepClone<T>(this T? obj)
{
    return FastCloner.FastCloner.DeepClone(obj);
}

Clone via Source Generator

[FastClonerClonable]
public class GenericClass<T>
{
    public T Value { get; set; }
}

public class MyClass
{
    public string StrVal { get; set; }
}

// [FastClonerClonable] is only required on types where you call .FastDeepClone()
var original = new GenericClass<List<MyClass>> { Value = new List<MyClass> { new MyClass { StrVal = "hello world" } } };
var clone = original.FastDeepClone();

Advanced Usage

Customizing Clone Behavior

FastCloner supports behavior attributes that control how types and members are cloned:

Behavior Effect
Clone Deep recursive copy
Reference Return original instance unchanged
Shallow MemberwiseClone without recursion
Ignore Return default

Compile-time (Attributes)

Apply attributes to types or members. Member-level attributes override type-level:

[FastClonerReference]  // Type-level: all usages preserve reference
public class SharedService { }

public class MyClass
{
    public SharedService Svc { get; set; }      // Uses type-level → Reference
    
    [FastClonerBehavior(CloneBehavior.Clone)]   // Member-level override → Clone
    public SharedService ClonedSvc { get; set; }
    
    [FastClonerIgnore]                          // → null/default
    public CancellationToken Token { get; set; }
    
    [FastClonerShallow]                         // → Reference copied directly
    public ParentNode Parent { get; set; }
}

Shorthand attributes: [FastClonerIgnore], [FastClonerShallow], [FastClonerReference]
Explicit: [FastClonerBehavior(CloneBehavior.X)]

Runtime (Reflection only)

Configure type behavior dynamically. Runtime settings are checked before attributes:

FastCloner.FastCloner.SetTypeBehavior<MySingleton>(CloneBehavior.Reference);
FastCloner.FastCloner.ClearTypeBehavior<MySingleton>();    // Reset one
FastCloner.FastCloner.ClearAllTypeBehaviors();             // Reset all

Note: Changing runtime behavior invalidates the cache. Try to configure once at startup, or use compile-time attributes when possible.

External ignore attributes

Models often already carry framework-level ignore attributes ([JsonIgnore], [BsonIgnore], [NotMapped], ...). Instead of stacking [FastClonerIgnore] on every such member, register those attribute types once per assembly:

[assembly: FastClonerExternalIgnore(typeof(JsonIgnoreAttribute), typeof(BsonIgnoreAttribute))]

Members carrying a registered attribute are treated as if they had [FastClonerIgnore]. The registration is declared on the assembly whose members it governs, so it is resolved statically:

  • works identically for the reflection cloner and the source generator - the source generator reads the same attribute at compile time,
  • zero runtime cost - decisions are baked into generated/compiled cloners like any [FastClonerIgnore]; no cache invalidation, no per-clone checks, AOT-safe,
  • registrations match the exact attribute type or any of its base classes; attribute presence only (constructors and properties like JsonIgnore(Condition = ...) are not evaluated).

An explicit member-level [FastClonerBehavior(...)] always wins over a registered external attribute.

Precedence (highest to lowest)

  1. Runtime SetTypeBehavior<T>()
  2. Member-level attribute
  3. Registered external ignore attribute
  4. Type-level attribute on member's type
  5. Default behavior

Cache Management

FastCloner.FastCloner.ClearCache();  // Free memory from reflection cache

Generic Classes and Abstract Types

The source generator automatically discovers which concrete types your generic classes and abstract hierarchies are used with:

Generic types - The generator scans your codebase for usages like MyClass<int> or MyClass<Customer> and generates specialized cloning code:

[FastClonerClonable]
public class Container<T>
{
    public T Value { get; set; }
}

// Source generator finds this usage and generates cloning code for Container<int>
var container = new Container<int> { Value = 42 };
var clone = container.FastDeepClone();

Abstract classes - The generator automatically finds all concrete derived types in your codebase:

[FastClonerClonable]
public abstract class Animal
{
    public string Name { get; set; }
}

public class Dog : Animal
{
    public string Breed { get; set; }
}

public class Cat : Animal
{
    public bool IsIndoor { get; set; }
}

// Cloning via the abstract type works - the generator discovered Dog and Cat
Animal pet = new Dog { Name = "Buddy", Breed = "Labrador" };
Animal clone = pet.FastDeepClone(); // Returns a cloned Dog

Non-abstract base classes - dispatch is not automatic for concrete types. Opt in per hierarchy root with [FastClonerPolymorphic]:

[FastClonerClonable]
[FastClonerPolymorphic]
public class Device
{
    public string Name { get; set; }
}

public class Phone : Device
{
    public string OS { get; set; }
}

Device device = new Phone { Name = "Pixel", OS = "Android" };
Device clone = device.FastDeepClone();

Explicitly Including Types

When a type is only used dynamically (not visible at compile time), use [FastClonerInclude] to ensure the generator creates cloning code for it:

[FastClonerClonable]
[FastClonerInclude(typeof(