Helper methods that deal with deep cloning objects (copying an object without a memory reference).
$ dotnet add package CommonNetFuncs.DeepCloneThis project contains helper methods for deep cloning objects in .NET applications (i.e. creating a new instance of an object with the same values as an existing instance but without the same references in memory).
Use expression trees to deep clone objects. This is by far the fastest of the three deep clone methods in this package with a minor penalty for the first clone of each unique type to construct the expression tree.
Deep clone an object using expression trees.
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Person original = new() { Name = "Chris", Age = "34" };
Person clone = original.DeepClone();
clone.Name = "Nick"; // Clone's Name property == "Nick" while original's Name property remains "Chris"
Use reflection to deep clone objects. In most cases this is the second fastest option of the three deep clone methods in this package.
Deep clone an object using reflection.
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Person original = new() { Name = "Chris", Age = "34" };
Person clone = original.DeepCloneR();
clone.Name = "Nick"; // Clone's Name property == "Nick" while original's Name property remains "Chris"
Use JSON serialization to deep clone objects. In most cases this is the slowest option of the three deep clone methods in this package.
Deep clone an object using JSON serialization.
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Person original = new() { Name = "Chris", Age = "34" };
Person clone = original.DeepCloneS();
clone.Name = "Nick"; // Clone's Name property == "Nick" while original's Name property remains "Chris"