RSCG – Dolly
 
 
| name | Dolly | 
| nuget | https://www.nuget.org/packages/Dolly/ | 
| link | https://github.com/AnderssonPeter/Dolly | 
| author | Peter Andersson | 
Clone objects with ease.
This is how you can use Dolly .
The code that you start with is
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net9.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Dolly" Version="0.0.7">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>
	<PropertyGroup>
		<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
		<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
	</PropertyGroup>
</Project>
The code that you will use is
// See https://aka.ms/new-console-template for more information using CloneData; Console.WriteLine("Hello,World!"); Person p = new (); p.FirstName = "Andrei"; p.LastName = "Ignat"; p.Age = 54; var p1=p.DeepClone(); Console.WriteLine(p1.Name());
namespace CloneData;
[Dolly.Clonable]
public partial class Person
{
    public string FirstName { get; set; } = "";
    public string LastName { get; set; } = "";
    [Dolly.CloneIgnore]
    public int Age { get; set; }
    public string Name() => $"{FirstName} {LastName}";
    public Person[] Childs { get; set; } = [];
}
The code that is generated is
using System;
namespace Dolly
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
    public class ClonableAttribute : Attribute
    {
    }
}
using System;
namespace Dolly
{
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
    public class CloneIgnoreAttribute : Attribute
    {
    }
}
using System;
namespace Dolly
{
    public interface IClonable<T> : ICloneable
    {
        T DeepClone();
        T ShallowClone();
    }
}
using Dolly;
using System.Linq;
namespace CloneData;
partial class Person : IClonable<Person>
{
    object ICloneable.Clone() => this.DeepClone();
    public virtual Person DeepClone() =>
        new ()
        {
            FirstName = FirstName,
            LastName = LastName,
            Childs = Childs.Select(item => item.DeepClone()).ToArray()
        };
    public virtual Person ShallowClone() =>
        new ()
        {
            FirstName = FirstName,
            LastName = LastName,
            Childs = Childs.ToArray()
        };
}
Code and pdf at
https://ignatandrei.github.io/RSCG_Examples/v2/docs/Dolly
Leave a Reply