Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
U

UnitGenerator

> 编程语言
Open source

C# Source Generator to create value-object, inspired by units of measure.

398 stars0 likes1 views
WebsiteGitHub

About

C# Source Generator to create value-object, inspired by units of measure.

UnitGenerator

C# Source Generator to create Value object pattern, also inspired by units of measure to support all arithmetic operators and serialization.

NuGet: UnitGenerator

Install-Package UnitGenerator

Execute in Unity Game Engine is also supported, please see the Unity section for details.

Introduction

For example, Identifier, UserId is comparable only to UserId, and cannot be assigned to any other type. Also, arithmetic operations are not allowed.

csharp
using UnitGenerator;

[UnitOf(typeof(int))]
public readonly partial struct UserId; { }

or when using C#11 and NET7 you can use

csharp
using UnitGenerator;

[UnitOf] public readonly partial struct UserId;

will generates

…

However, Hp in games, should not be allowed to be assigned to other types, but should support arithmetic operations with int. For example double heal = target.Hp = Hp.Min(target.Hp * 2, target.MaxHp).

…

You can configure with UnitGenerateOptions, which method to implement.

csharp
[Flags]
enum UnitGenerateOptions
{
    None = 0,
    ImplicitOperator = 1,
    ParseMethod = 1  { Value = 1111 }` is awful. The value-object should be serialized natively, i.e. `Serialize(useId) => 1111`, and should be able to be added directly to a database, etc.

Currently UnitGenerator supports [MessagePack for C#](https://github.com/MessagePack-CSharp/MessagePack-CSharp), System.Text.Json(JsonSerializer), [Dapper](https://github.com/StackExchange/Dapper) and EntityFrameworkCore.

```csharp
[UnitOf(UnitGenerateOptions.MessagePackFormatter)]
public readonly partial struct UserId;

// -- generates

[MessagePackFormatter(typeof(UserIdMessagePackFormatter))]
public readonly partial struct UserId 
{
    class UserIdMessagePackFormatter : IMessagePackFormatter
    {
        public void Serialize(ref MessagePackWriter writer, UserId value, MessagePackSerializerOptions options)
        {
            options.Resolver.GetFormatterWithVerify().Serialize(ref writer, value.value, options);
        }

        public UserId Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
        {
            return new UserId(options.Resolver.GetFormatterWithVerify().Deserialize(ref reader, options));
        }
    }
}

…

csharp
namespace UnitGenerator
{
    [AttributeUsage(AttributeTargets.Struct, AllowMultiple = false)]
    internal class UnitOfAttribute : Attribute
    {
        public Type Type { get; }
        public UnitGenerateOptions Options { get; }
        public UnitArithmeticOperators ArithmeticOperators { get; set; }
        public string? ToStringFormat { get; set; }
        
        public UnitOfAttribute(Type type, UnitGenerateOptions options = UnitGenerateOptions.None) { ... }
    }

#if NET7_0_OR_GREATER
    [AttributeUsage(AttributeTargets.Struct, AllowMultiple = false)]
    internal class UnitOfAttribute : Attribute
    {
        public Type Type { get; }
        public UnitGenerateOptions Options { get; }
        public UnitArithmeticOperators ArithmeticOperators { get; set; } = UnitArithmeticOperators.All;
        public string? ToStringFormat { get; set; }

        public UnitOfAttribute(UnitGenerateOptions options = UnitGenerateOptions.None)
        {
            this.Type = typeof(T);
            this.Options = options;
        }
    }
#endif
}

You can attach this attribute with any specified underlying type to readonly partial struct.

csharp
[UnitOf(typeof(Guid))]
public readonly partial struct GroupId { }

[UnitOf(typeof(string))]
public readonly partial struct Message { }

[UnitOf(typeof(long))]
public readonly partial struct Power { }

[UnitOf(typeof(byte[]))]
public readonly partial struct Image { }

[UnitOf(typeof(DateTime))]
public readonly partial struct StartDate { }

[UnitOf(typeof((string street, string city)))]
public readonly partial struct StreetAddress { }

Standard UnitOf(UnitGenerateOptions.None) generates value constructor, explicit operator, implement IEquatable, override GetHashCode, override ToString, == and != operator, TypeConverter for ASP.NET Core binding, AsPrimitive method.

If you want to retrieve primitive value, use AsPrimitive() instead of .Value. This is intended to avoid casual getting of primitive values (using the arithmetic operator option if available).

When type is bool, also implements true, false, ! operators.

csharp
public static bool operator true(Foo x) => x.value;
public static bool operator false(Foo x) => !x.value;
public static bool operator !(Foo x) => !x.value;

When type is Guid or Ulid, also implements New() and New***() static operator.

For Guid type in .NET 9.0 or later, these methods accept an optional uuidV7 parameter. When uuidV7 is set to true, the methods use Guid.CreateVersion7() internally.

csharp
public static GroupId New();
public static GroupId NewGroupId();
// overload .NET 9.0+
public static GroupId New(bool uuidV7);
public static GroupId NewGroupId(bool uuidV7);

Second parameter UnitGenerateOptions options can configure which method to implement, default is None.

Optional named parameter: ArithmeticOperators can configure which generates operators specifically. Default is Number. (This can be used if UnitGenerateOptions.ArithmeticOperator is specified.)

Optional named parameter: ToStringFormat can configure ToString format. Default is null and output as ${0}.

UnitGenerateOptions

When referring to the UnitGenerator, it generates a internal UnitGenerateOptions that is bit flag of which method to implement.

csharp
[Flags]
internal enum UnitGenerateOptions
{
    None = 0,
    ImplicitOperator = 1,
    ParseMethod = 2,
    MinMaxMethod = 4,
    ArithmeticOperator = 8,
    ValueArithmeticOperator = 16,
    Comparable = 32,
    Validate = 64,
    JsonConverter = 128,
    MessagePackFormatter = 256,
    DapperTypeHandler = 512,
    EntityFrameworkValueConverter = 1024,
}

You can use this with [UnitOf].

csharp
[UnitOf(typeof(int), UnitGenerateOptions.ArithmeticOperator | UnitGenerateOptions.ValueArithmeticOperator | UnitGenerateOptions.Comparable | UnitGenerateOptions.MinMaxMethod)]
public readonly partial struct Strength { }

[UnitOf(typeof(DateTime), UnitGenerateOptions.Validate | UnitGenerateOptions.ParseMethod | UnitGenerateOptions.Comparable)]
public readonly partial struct EndDate { }

[UnitOf(typeof(double), UnitGenerateOptions.ParseMethod | UnitGenerateOptions.MinMaxMethod | UnitGenerateOptions.ArithmeticOperator | UnitGenerateOptions.ValueArithmeticOperator | UnitGenerateOptions.Comparable | UnitGenerateOptions.Validate | UnitGenerateOptions.JsonConverter | UnitGenerateOptions.MessagePackFormatter | UnitGenerateOptions.DapperTypeHandler | UnitGenerateOptions.EntityFrameworkValueConverter)]
public readonly partial struct AllOptionsStruct { }

You can setup project default options like this.

csharp
internal static class UnitOfOptions
{
    public const UnitGenerateOptions Default = UnitGenerateOptions.ArithmeticOperator | UnitGenerateOptions.ValueArithmeticOperator | UnitGenerateOptions.Comparable | UnitGenerateOptions.MinMaxMethod;
}

[UnitOf(typeof(int), UnitOfOptions.Default)]
public readonly partial struct Hp { }

ImplicitOperator

csharp
// Default
public static explicit operator U(T value) => value.value;
public static explicit operator T(U value) => new T(value);

// UnitGenerateOptions.ImplicitOperator
public static implicit operator U(T value) => value.value;
public static implicit operator T(U value) => new T(value);

ParseMethod

csharp
public static T Parse(string s)
public static bool TryParse(string s, out T result)

MinMaxMethod

csharp
public static T Min(T x, T y)
public static T Max(T x, T y)

ArithmeticOperator

csharp
public static T operator +(in T x, in T y) => new T(checked((U)(x.value + y.value)));
public static T operator -(in T x, in T y) => new T(checked((U)(x.value - y.value)));
public static T operator *(in T x, in T y) => new T(checked((U)(x.value * y.value)));
public static T operator /(in T x, in T y) => new T(checked((U)(x.value / y.value)));
public static T operator +(T value) => new((U)(+value.value));
public static T operator -(T value) => new((U)(-value.value));
public static T operator ++(T x) => new T(checked((U)(x.value + 1)));
public static T operator --(T x) => new T(checked((U)(x.value - 1)));

In addition, all members conforming to System.Numerics.INumber are generated.

If you want to suppress this and generate only certain operators, you can use the the ArithmeticOperatros option of [UnitOf] attribute as follows:

csharp
[UnitOf(
    typeof(int), 
    UnitGenerateOptions.ArithmeticOperator,
    ArithmeticOperators = UnitArithmeticOperators.Addition | UnitArithmeticOperators.Subtraction)]
public readonly partial struct Hp { }

…

csharp
public static T operator +(in T x, in U y) => new T(checked((U)(x.value + y)));
public static T operator -(in T x, in U y) => new T(checked((U)(x.value - y)));
public static T operator *(in T x, in U y) => new T(checked((U)(x.value * y)));
public static T operator /(in T x, in U y) => new T(checked((U)(x.value / y)));

Comparable

Implements IComparable and >, =, value.CompareTo(other.value); public static bool operator >(in T x, in T y) => x.value > y.value; public static bool operator x.value =(in T x, in T y) => x.value >= y.value; public static bool operator x.value, =, ` 9999) throw new Exception("Invalid value range: " + value); } }

// Source generator generate this codes. public T(int value) { this.value = value; this.Validate(); }

private partial void Validate();


### Normalize

Implements `partial void Normalize(ref T value)` method that is called on constructor.

```csharp
// You can implement this custom normalize method to change value during initialization
[UnitOf(typeof(int), UnitGenerateOptions.Normalize)]
public readonly partial struct SampleValidate
{
    // impl here.
    private partial void Normalize(ref int value)
    {
        value = Math.Max(value, 9999);
    }
}

// Source generator generate this codes.
public T(int value)
{
    this.value = value;
    this.Normalize(ref this.value);
}
 
private partial void Normalize(ref int value);

JsonConverter

Implements System.Text.Json's JsonConverter. It will be used JsonSerializer automatically.

csharp
[JsonConverter(typeof(UserIdJsonConverter))]
public readonly partial struct UserId
{
    class UserIdJsonConverter : JsonConverter
}

JsonConverterDictionaryKeySupport

Implements JsonConverter's WriteAsPropertyName/ReadAsPropertyName. It supports from .NET 6, supports Dictionary's Key.

csharp
var dict = Dictionary
JsonSerializer.Serialize(dict);

MessagePackFormatter

Implements MessagePack for C#'s MessagePackFormatter. It will be used MessagePackSerializer automatically.

csharp
[MessagePackFormatter(typeof(UserIdMessagePackFormatter))]
public readonly partial struct UserId
{
    class UserIdMessagePackFormatter : IMessagePackFormatter
}

DapperTypeHandler

Implements Dapper's TypeHandler by public accessibility. TypeHandler is automatically registered at the time of Module initialization.

csharp
public readonly partial struct UserId
{
    public class UserIdTypeHandler : Dapper.SqlMapper.TypeHandler
}

[ModuleInitializer]
public static void AddTypeHandler()
{
    Dapper.SqlMapper.AddTypeHandler(new A.ATypeHandler());
}

EntityFrameworkValueConverter

Implements

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

C#

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言