Skip to content

lofcz/FastCloner

Repository files navigation

FastCloner FastCloner.Contrib

FastCloner

Te Reo Icon Fast deep cloning library for .NET 8+. Supports both deep and shallow cloning. Extensively tested, focused on performance and stability even on complicated object graphs. FastCloner is designed to work with as few gotchas as possible out of the box. The mapping is zero-config by default. Clone your objects and be done with it fast. FastCloner builds upon DeepClone.



Getting Started

Install the package via NuGet:

dotnet add package FastCloner
dotnet add package FastCloner.Contrib # only required for some special types, such as Fonts

Clone your objects:

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

That's it! Feel free to map this method to your extension so if you need to migrate in the future it's a matter of just switching that method. We intentionally don't ship our own .DeepClone() extension method.

Advanced usage

Sometimes you might want to exclude certain fields & properties from cloning:

private class TestPropsWithIgnored
{
    public int A { get; set; } = 10;
    [FastClonerIgnore] // <-- decorate such members with [FastClonerIgnore]
    public string B { get; set; } = "My string";
}

TestPropsWithIgnored original = new TestPropsWithIgnored { A = 42, B = "Test value" };
TestPropsWithIgnored clone = original.DeepClone(); // clone.B is null (default value of a given type)

Apart from deep cloning, FastCloner supports shallow cloning and deep cloning to target:

// the list is shared between the two instances
var clone = FastCloner.ShallowClone(new { Hello = "world", MyList = new List<int> { 1 } });

Limitations

FastCloner uses caching by default which makes evaluating properties harder. Unmanaged resources, such as IntPtrs can't be cloned as there are no metadata for length. ReadOnly collections are tested to behave well as long as they follow basic conventions. Many other features, such as cloning Dictionaryies properly while keeping hashcodes, INotifyPropertyChanged, delegates, events, HttpRequests / responses, and others are supported. If something doesn't work out of the box let me know in the issues, the repository is actively maintained.

License

MIT, simple 💜