Code-generator to fix your Primitive Obsession.
$ dotnet add package Dalion.ValueObjectsA C# code generator to cure Primitive Obsession.
ValueObjects is a .NET Source Generator and analyzer. It turns your primitives (ints, decimals etc.) into value objects that represent domain concepts (CustomerId, AccountBalance, etc.).
All generated code is compatible with C# 11.0 or higher and .NET 8.0 or higher.
Add the Dalion.ValueObjects NuGet package to your project.
<ItemGroup>
<PackageReference
Include="Dalion.ValueObjects"
Version="[1.1.0,)"
ReferenceOutputAssembly="false"
OutputItemType="Analyzer"
/>
</ItemGroup>
Then, create a readonly partial record struct and annotate it with the [ValueObject<T>] attribute:
using System;
[ValueObject<Guid>]
public readonly partial record struct CustomerId;
This enables the following for the type:
String representation based on the underlying primitive valueSystem.Text.Json Serialization and deserialization supportTypeConverter support (see Type Conversion in .NET)public static readonly fields (even if they are considered to be invalid)IComparable and IComparable<T>IFormattable for formatting supportIParsable<T> for parsing supportISpanParsable<T> for span parsing support, and IUtf8SpanParsable<T> for UTF8 span parsing support (if the underlying type supports it)Empty (name is configurable) that represents the default value for the value object typeIt makes it possible to enable the following for the type, using arguments in the attribute to configure behavior:
string-based value objects)== and !=) based on the underlying primitive value32.Celsius())This library also enables multiple roslyn analyzers that validate correct usage of the [ValueObject<T>] attribute and the annotated types.
You can examine the generated code in the generated sample code files. The behavior of the generated types is documented by unit tests.
Similarly, the behavior of the roslyn analyzers is documented by unit tests.
All generated code is compatible with C# 11.0 or higher and .NET 8.0 or higher.
See the Wiki for more detailed information, such as getting started, tutorials, and how-tos.
Creating value objects is a repetitive task. This project aims to reduce the amount of boilerplate code that needs to be written, by generating it.
Inspired by the awesome Vogen project.