Fast deep cloning using compiled expression trees for nested objects, collections, and circular references.
dotnet add package Philiprehberger.DeepCloneFast deep cloning using compiled expression trees for nested objects, collections, and circular references.
dotnet add package Philiprehberger.DeepClone
using Philiprehberger.DeepClone;
var original = new Person { Name = "Alice", Age = 30 };
var clone = DeepClone.Clone(original);
// Or use the extension method
var clone2 = original.DeepClone();
var team = new Team
{
Name = "Engineering",
Members = new List<Person>
{
new() { Name = "Alice", Age = 30 },
new() { Name = "Bob", Age = 25 }
}
};
var clonedTeam = team.DeepClone();
clonedTeam.Members[0].Name = "Charlie";
// original.Members[0].Name is still "Alice"
var original = new Person { Name = "Alice", Age = 30 };
var modified = DeepClone.CloneWith(original, p => p.Name = "Bob");
// modified.Name is "Bob", modified.Age is 30
// original.Name is still "Alice"
// Or use the extension method
var modified2 = original.DeepCloneWith(p => p.Age = 25);
var node = new TreeNode { Value = "root" };
node.Children.Add(new TreeNode { Value = "child", Parent = node });
// Circular references are handled automatically
var clonedTree = node.DeepClone();
DeepClone| Method | Description |
|---|---|
Clone<T>(T obj) | Create a deep clone of the given object |
CloneWith<T>(T obj, Action<T> configure) | Deep clone then apply property overrides |
| Method | Description |
|---|---|
DeepClone<T>(this T obj) | Extension method for deep cloning any object |
DeepCloneWith<T>(this T obj, Action<T> configure) | Extension method for deep cloning with property overrides |
| Type | Behavior |
|---|---|
| Primitives | Passed through (value types) |
string | Passed through (immutable) |
| Arrays | Element-wise deep clone |
List<T> | Element-wise deep clone |
Dictionary<K, V> | Key/value deep clone |
| Classes | Property-by-property deep clone |
| Structs | Property-by-property deep clone |
dotnet build src/Philiprehberger.DeepClone.csproj --configuration Release
If you find this project useful: