Skip to content

About

AOT-compatible C# Source Generators for DeepCopy, DeepEqual, and Model-ViewModel DeepMap.

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

Deep Extensions

Deep Extensions is a zero-reflection, AOT-compatible, and trimmable .NET library powered by Roslyn Source Generation. It eliminates boilerplate code with three core features:

  • DeepCopy: Recursive object cloning with automatic circular reference handling.
  • DeepEqual: Recursive value-based equality comparisons.
  • DeepMap: Explicit Model-to-ViewModel synchronization supporting collections, custom property names, and value converters.

Designed for seamless integration with CommunityToolkit.Mvvm, WPF, WinUI, and Avalonia, complete with built-in Roslyn analyzers for clear compiler diagnostics.

Table of Contents

Features

  • Roslyn Code Generator
  • AOT-compatible
  • Trimmable
  • CommunityToolkit.Mvvm compatible.
  • WPF, WinUI, and Avalonia compatible.
  • Resolving circular references during deep copy

Installation

Nuget Link

https://www.nuget.org/packages/DeepExtensions

PackageReference

<PackageReference Include="DeepExtensions" Version="0.5.0" />

.NET CLI-Befehl

> dotnet add package DeepExtensions

Built-in Roslyn analyzers & clear compiler diagnostics

  • DEEPGEN001 Class is not partial

Problems and Sulution

  • In the event of issues caused by duplicate generation in nested libraries, the following may help:
<PackageReference Include="DeepExtensions" Version="0.5.0" PrivateAssets="all" />

DeepCopy

Generates code for deep copy.

An opt-out / automatic matching approach is used. This means that all properties not marked with [DeepCopyIgnore] will be copied.

Attributes

[DeepCopy]

The [DeepCopy] attribute only needs to be placed on the root element; it signals that a deep copy should be generated recursively for this class, all its base classes, and all its property classes.

[DeepCopyIgnore]

All properties with [DeepCopyIgnore] will be ignored.

Examples

using DeepExtensions;

namespace Demo.Models;

[DeepCopy]
public partial class DemoModel : BaseModel
{
    public string Name { get; set; } = "Peter";

    public SubModel? Sub { get; set; } = new SubModel();

    [DeepCopyIgnore]
    public int Num { get; set; } = 45;
}

public partial class BaseModel
{
    public int Id { get; set; } = 1;
}
Generated by DeepExtensions
partial class DemoModel : IDeepCopy<DemoModel>
{
    public CopyBaseModel DeepCopy()
    {
        return DeepCopy(new Dictionary<object, object>(ReferenceEqualityComparer.Instance));
    }

    public new DemoModel DeepCopy(Dictionary<object, object>? visited)
    {
        if (visited is not null && visited.TryGetValue(this, out var existing))
        {
            return (DemoModel)existing;
        }
        var copy = new DemoModel();
        if (visited != null)
        {
            visited[this] = copy;
        }
        DeepCopyTo(copy, visited);
        return copy;
    }

    protected void DeepCopyTo(DemoModel target, Dictionary<object, object> visited)
    {
        base.DeepCopyTo(target, visited);
        target.Name = this.Name;
        target.Sub = this.Sub?.DeepCopy(visited);
    }
}

partial class BaseModel : IDeepCopy<BaseModel>
{
    public BaseModel DeepCopy()
    {
        return DeepCopy(new Dictionary<object, object>(ReferenceEqualityComparer.Instance));
    }

    public BaseModel DeepCopy(Dictionary<object, object>? visited)
    {
        if (visited is not null && visited.TryGetValue(this, out var existing))
        {
            return (BaseModel)existing;
        }
        var copy = new BaseModel();
        if (visited != null)
        {
            visited[this] = copy;
        }
        DeepCopyTo(copy, visited);
        return copy;
    }

    protected void DeepCopyTo(BaseModel target, Dictionary<object, object>? visited)
    {
        target.Id = this.Id;
    }
}

DeepEqual

Generates code for deep equal.

An opt-out / automatic matching approach is used. This means that all properties not marked with [DeepEqualIgnore] will be compared.

Attributes

[DeepEqual]

The [DeepEqual] attribute only needs to be placed on the root element; it signals that a deep equal should be generated recursively for this class, all its base classes, and all its property classes.

[DeepEqualIgnore]

All properties with [DeepEqualIgnore] will be ignored.

Examples

using DeepExtensions;

namespace Demo.Models;

[DeepEqual]
public partial class DemoModel
{
    public string Name { get; set; } = "Peter";

    public SubModel Sub { get; set; } = new SubModel();

    [DeepEqualIgnore]
    public int Num { get; set; } = 45;
}

// Generated

partial class DemoModel : IDeepEqual<DemoModel>
{
    public bool DeepEqual(DemoModel? value)
    {
        if (value is null) return false;
        return
            Name == value.Name &&
            ((Sub is null && value.Sub is null) || (Sub is not null && Sub.DeepEqual(value.Sub)));
    }
}

DeepMap

Mapping between Model and ViewModel trees

  • Custom converters

Attributes

In contrast to DeepCopy and DeepEqual, this approach uses explicit opt-in. This means that all properties intended for mapping must be decorated with [DeepMapProperty].

Examples

Simple Types

Synchronizing properties with simple data types between the Model and the ViewModel.

Model
using DeepExtensions;

namespace Demo.Models;

public class DemoModel
{
    public string Name { get; set; } = "Peter";
}
ViewModel

for C# 13 / .NET 9 and CommunityToolkit.Mvvm 8.4+ only

using CommunityToolkit.Mvvm.ComponentModel;
using DeepExtensions;

namespace Demo.ViewModels;

[DeepMap(typeof(DemoModel))]
public partial class DemoViewModel : ObservableObject
{
    [ObservableProperty]
    [DeepMapProperty]
    public partial string Name { get; set; }
}

List of Simple Types

Synchronizing properties with a list of simple data types between the Model and the ViewModel.

Model
namespace Demo.Models;

public class DemoModel
{
    public List<string> Names { get; set; } = [ "Peter", "Paul", "Mary"];
}
ViewModel
using CommunityToolkit.Mvvm.ComponentModel;
using DeepExtensions;

namespace Demo.ViewModels;

[DeepMap(typeof(DemoModel))]
public partial class DemoViewModel : ObservableObject
{
    // no partial, no set, no nullable, and no [ObservableProperty]
    [DeepMapProperty]
    public ObservableCollection<string> Names { get; }
}

Different Names

Synchronizing properties with different names between Model and ViewModel.

Model
namespace Demo.Models;

public class DemoModel
{
    public string Name { get; set; } = "Peter";
}
ViewModel
using CommunityToolkit.Mvvm.ComponentModel;
using DeepExtensions;

namespace Demo.ViewModels;

[DeepMap(typeof(DemoModel))]
public partial class DemoViewModel : ObservableObject
{
    [ObservableProperty]
    [DeepMapProperty(nameof(DemoModel.Name))]
    public partial string FirstName { get; set; }
}

Children

Synchronizing properties with children between Model and ViewModel.

Model
namespace Demo.Models;

public class RootModel
{
    public LeafModel? Leaf { get; set; } = new LeafModel();
}

public class LeafModel
{
    public string Name { get; set; } = "Peter";
}
ViewModel
using CommunityToolkit.Mvvm.ComponentModel;
using DeepExtensions;

namespace Demo.ViewModels;

[DeepMap(typeof(RootModel))]
public partial class RootViewModel : ObservableObject
{
    [ObservableProperty]
    [DeepMapProperty]
    public partial LeafViewModel? Leaf { get; set; }
}

[DeepMap(typeof(LeafModel))]
public partial class LeafViewModel : ObservableObject
{
    [ObservableProperty]
    [DeepMapProperty]
    public partial string Name { get; set; }
}

List of Children

Synchronizing properties with a list of children between Model and ViewModel.

Model
namespace Demo.Models;

public class RootModel
{
    public List<LeafModel> Leaves { get; set; } = [new LeafModel(), new LeafModel()];
}

public class LeafModel
{
    public string Name { get; set; } = "Peter";
}
ViewModel
using CommunityToolkit.Mvvm.ComponentModel;
using DeepExtensions;

namespace Demo.ViewModels;

[DeepMap(typeof(RootModel))]
public partial class RootViewModel : ObservableObject
{
    // no partial, no set, no nullable, and no [ObservableProperty]
    [DeepMapProperty]
    public ObservableCollection<LeafViewModel> Leaves { get; }
}

[DeepMap(typeof(LeafModel))]
public partial class LeafViewModel : ObservableObject
{
    [ObservableProperty]
    [DeepMapProperty]
    public partial string Name { get; set; }
}

Converter Functions

Synchronizing properties with converters between the Model and the ViewModel. The converters can also be applied to lists and "list to simpleType" mappings.

Model
namespace Demo.Models;

public class DemoModel
{
    public int Num { get; set; } = 25;
}
ViewModel
using CommunityToolkit.Mvvm.ComponentModel;
using DeepExtensions;

namespace Demo.ViewModels;

[DeepMap(typeof(DemoModel))]
public partial class DemoViewModel : ObservableObject
{
    [ObservableProperty]
    [DeepMapProperty(Converter = "NumConvert")]
    public partial string Num { get; set; }

    private string GetNumConvert(int val) => val.ToString();
    private int SetNumConvert(string val) => int.Parse(val);
}

Converter Interface

Synchronizing properties with converters between the Model and the ViewModel. The converters can also be applied to lists and "list to simpleType" mappings.

Model
namespace Demo.Models;

public class DemoModel
{
    public int Num { get; set; } = 25;
}
ViewModel
using CommunityToolkit.Mvvm.ComponentModel;
using DeepExtensions;

namespace Demo.ViewModels;

[DeepMap(typeof(DemoModel))]
public partial class DemoViewModel : ObservableObject
{
    [ObservableProperty]
    [DeepMapProperty(ConverterType = typeof(IntToStringConverter))]
    public partial string Num { get; set; }

    public class IntToStringConverter : IDeepMapPropertyConverter
    {
        public object Convert(object value) => value?.ToString()!;
        public object ConvertBack(object value) => (value is string input && int.TryParse(input, out int result)) ? result : null!;
    }
}

Examples of use

Undo and Redo with DeepCopy

public partial class PlanController
{
#if DEBUG
    private readonly bool IsHistoryEnabled = false;
#else
    private readonly bool IsHistoryEnabled = true;
#endif

    public PlanController()
    {
        var plan = Plan.New();
        if (IsHistoryEnabled)
        {
            history.Add(plan);
            CurrentPlan = plan.DeepCopy();
        }
        else
        {
            CurrentPlan = plan;
        }
    }

    private readonly List<Plan> history = [];

    private int historyPosition = 0;

    public Plan CurrentPlan { get; private set; }

    public bool CanUndo => IsHistoryEnabled && historyPosition > 0;

    public bool CanRedo => IsHistoryEnabled && historyPosition < history.Count - 1;

    public void Undo()
    {
        if (CanUndo)
        {
            CurrentPlan = history[--historyPosition].DeepCopy(); 
            OnUpdateVisual();
        }
    }

    public void Redo()
    {
        if (CanRedo)
        {
            CurrentPlan = history[++historyPosition].DeepCopy(); 
            OnUpdateVisual();
        }
    }

    private void Update()
    {
        if (!IsHistoryEnabled) return;

        // remove eveything behind historyPosition
        if (historyPosition < history.Count - 1)
        {
            history.RemoveRange(historyPosition + 1, history.Count - historyPosition - 1);
        }

        history.Add(CurrentPlan.DeepCopy());
        historyPosition = history.Count - 1;

    }
}

About

AOT-compatible C# Source Generators for DeepCopy, DeepEqual, and Model-ViewModel DeepMap.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages