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

Vogen

> 编程语言
Open source

A semi-opinionated library which is a source generator and a code analyser. It Source generates Value Objects

1.5K stars0 likes0 views
WebsiteGitHub

About

A semi-opinionated library which is a source generator and a code analyser. It Source generates Value Objects

## Give a Star! :star: If you like or are using this project please give it a star. Thanks!

Vogen: cure your Primitive Obsession

Vogen (pronounced "Voh Jen") is a .NET Source Generator and analyzer. It turns your primitives (ints, decimals etc.) into value objects that represent domain concepts (CustomerId, AccountBalance etc.)

It adds new C# compilation errors to help stop the creation of invalid value objects.

This readme covers some of the functionality. Please see the Wiki for more detailed information, such as getting started, tutorials, and how-tos.

Overview

The source generator generates strongly typed domain concepts. You provide this:

csharp
[ValueObject<int>]
public partial struct CustomerId;

... and Vogen generates source similar to this:

…

You then use CustomerId instead of int in your domain in the full knowledge that it is valid and safe to use:

csharp
CustomerId customerId = CustomerId.From(123);
SendInvoice(customerId);
...

public void SendInvoice(CustomerId customerId) { ... }

(you'll see the default public constructor is created, but the analyzer stops you from using it, as described in a bit...)

int is the default type for value objects. It is generally a good idea to explicitly declare each type for clarity. You can also - individually or globally - configure them to be other types. See the Configuration section later in the document.

Here's some other examples:

csharp
[ValueObject<decimal>] 
public partial struct AccountBalance;

[ValueObject<string>]
public partial class LegalEntityName;

The main goal of Vogen is to ensure the validity of your value objects, the code analyser helps you to avoid mistakes which might leave you with uninitialized value objects in your domain.

It does this by adding new constraints in the form of new C# compilation errors. There are a few ways you could end up with uninitialized value objects. One way is by giving your type constructors. Providing your own constructors could mean that you forget to set a value, so Vogen doesn't allow you to have user defined constructors:

csharp
[ValueObject]
public partial struct CustomerId 
{
    // Vogen deliberately generates this so that you can't create your own:
    // error CS0111: Type 'CustomerId' already defines a member called 'CustomerId' 
    // with the same parameter type
    public CustomerId() { }

    // error VOG008: Cannot have user defined constructors, 
    // please use the From method for creation.
    public CustomerId(int value) { }
}

In addition, Vogen will spot issues when creating or consuming value objects:

…

One of the main goals of this project is to achieve almost the same speed and memory performance as using primitives directly. Put another way, if your decimal primitive represents an Account Balance, then there is extremely low overhead of using an AccountBalance value object instead. Please see the performance metrics below.


Installation

Vogen is a Nuget package. Install it with:

dotnet add package Vogen

When added to your project, the source generator generates the wrappers for your primitives and the code analyser will let you know if you try to create invalid value objects.

Usage

Think about your domain concepts and how you use primitives to represent them, e.g. instead of this:

csharp
public void HandlePayment(int customerId, int accountId, decimal paymentAmount)

... have this:

csharp
public void HandlePayment(CustomerId customerId, AccountId accountId, PaymentAmount paymentAmount)

It's as simple as creating types like this:

csharp
[ValueObject] 
public partial struct CustomerId;

[ValueObject] 
public partial struct AccountId;

[ValueObject<decimal>] 
public partial struct PaymentAmount;

More on Primitive Obsession

The source generator generates value objects. value objects help combat Primitive Obsession by wrapping simple primitives such as int, string, double etc. in a strongly-typed type.

Primitive Obsession (AKA StringlyTyped) means being obsessed with primitives. It is a Code Smell that degrades the quality of software.

"Primitive Obsession is using primitive data types to represent domain ideas" #

Some examples:

  • instead of int age - we'd have Age age. Age might have validation that it couldn't be negative
  • instead of string postcode - we'd have Postcode postcode. Postcode might have validation on the format of the text

The source generator is opinionated. The opinions help ensure consistency. The opinions are:

  • A value object (VO) is constructed via a factory method named From, e.g. Age.From(12)
  • A VO is equatable (Age.From(12) == Age.From(12))
  • A VO, if validated, is validated with a static method named Validate that returns a Validation result
  • Any validation that is not Validation.Ok results in a ValueObjectValidationException being thrown

It is common to represent domain ideas as primitives, but primitives might not be able to fully describe the domain idea.
To use value objects instead of primitives, we simply swap code like this:

csharp
public class CustomerInfo {
    private int _id;
    public CustomerInfo(int id) => _id = id;
}

.. to this:

csharp
public class CustomerInfo {
    private CustomerId _id;
    public CustomerInfo(CustomerId id) => _id = id;
}

Tell me more about the Code Smell

There's a blog post here that describes it, but to summarise:

Primitive Obsession is being obsessed with the seemingly convenient way that primitives, such as ints and strings, allow us to represent domain objects and ideas.

It is this:

csharp
int customerId = 42

What's wrong with that?

A customer ID likely cannot be fully represented by an int. An int can be negative or zero, but it's unlikely a customer ID can be. So, we have constraints on a customer ID. We can't represent or enforce those constraints on an int.

So, we need some validation to ensure the constraints of a customer ID are met. Because it's in int, we can't be sure if it's been checked beforehand, so we need to check it every time we use it. Because it's a primitive, someone might've changed the value, so even if we're 100% sure we've checked it before, it still might need checking again.

So far, we've used as an example, a customer ID of value 42. In C#, it may come as no surprise that "42 == 42" (I haven't checked that in JavaScript!). But, in our domain, should 42 always equal 42? Probably not if you're comparing a Supplier ID of 42 to a Customer ID of 42! But primitives won't help you here (remember, 42 == 42!).

csharp
(42 == 42) // true
(SupplierId.From(42) == SupplierId.From(42)) // true
(SupplierId.From(42) == VendorId.From(42)) // compilation error

But sometimes, we need to denote that a value object isn't valid or has not been set. We don't want anyone outside of the object doing this as it could be used accidentally. It's common to have Unspecified instances, e.g.

csharp
public class Person {
    public Age Age { get; } = Age.Unspecified;
}

We can do that with an Instance attribute:

csharp
  [ValueObject]
  [Instance("Unspecified", -1)]
  public readonly partial struct Age {
      public static Validation Validate(int value) =>
          value > 0 ? Validation.Ok : Validation.Invalid("Must be greater than zero.");
  }

This generates public static Age Unspecified = new Age(-1);. The constructor is private, so only this type can (deliberately) create invalid instances.

Now, when we use Age, our validation becomes clearer:

csharp
public void Process(Person person) {
    if(person.Age == Age.Unspecified) {
        // age not specified.
    }
}

We can also specify other instance properties:

csharp
[ValueObject<float>]
[Instance("Freezing", 0)]
[Instance("Boiling", 100)]
public readonly partial struct Celsius {
    public static Validation Validate(float value) =>
        value >= -273 ? Validation.Ok : Validation.Invalid("Cannot be colder than absolute zero");
}

Configuration

Each value object can have its own optional configuration. Configuration includes:

  • The underlying type
  • Any 'conversions' (Dapper, System.Text.Json, Newtonsoft.Json, etc.) - see the Integrations page in the wiki for more information
  • The type of the exception that is thrown when validation fails

If any of those above are not specified, then global configuration is inferred. It looks like this:

csharp
[assembly: VogenDefaults(
    underlyingType: typeof(int), 
    conversions: Conversions.Default, 
    throws: typeof(ValueObjectValidationException))]

Those again are optional. If they're not specified, then they are defaulted to:

  • Underlying type = typeof(int)
  • Conversions = Conversions.Default (TypeConverter and System.Text.Json)
  • Validation exception type = typeof(ValueObjectValidationException)

There are several code analysis warnings for invalid configuration, including:

  • when you specify an exception that does not derive from System.Exception
  • when your exception does not have 1 public constructor that takes an int
  • when the combination of conversions does not match an entry

Performance

(to run these yourself: dotnet run -c Release --framework net9.0 -- --job short --filter * in the Vogen.Benchmarks folder)

As mentioned previously, the goal of Vogen is to achieve very similar performance compare to using primitives themselves. Here's a benchmark comparing the use of a validated value object with underlying type of int vs using an int natively (primitively )

ini
BenchmarkDotNet=v0.13.2, OS=Windows 11 (10.0.22621.1194)
AMD Ryzen 9 5950X, 1 CPU, 32 logical and 16 physical cores
.NET SDK=7.0.102
  [Host]   : .NET 7.0.2 (7.0.222.60605), X64 RyuJIT AVX2
  ShortRun : .NET 7.0.2 (7.0.222.60605), X64 RyuJIT AVX2
Job=ShortRun  IterationCount=3  LaunchCount=1  
WarmupCount=3    
Method Mean Error StdDev Ratio RatioSD Gen0 Allocated
UsingIntNatively 14.55 ns 1.443 ns 0.079 ns 1.00 0.00 - -
UsingValueObjectStruct 14.88 ns 3.639 ns 0.199 ns 1.02 0.02 - -

There is no discernible difference between using a native int and a VO struct; both are pretty much the same in terms of speed and memory.

The next most common scenario is using a VO class to represent a native String. These results are:

ini
BenchmarkDotNet=v0.13.2, OS=Windows 11 (10.0.22621.1194)
AMD Ryzen 9 5950X, 1 CPU, 32 logical and 16 physical cores
.NET SDK=7.0.102
  [Host]   : .NET 7.0.2 (7.0.222.60605), X64 RyuJIT AVX2
  ShortRun : .NET 7.0.2 (7.0.222.60605), X64 RyuJIT AVX2
Job=ShortRun  IterationCount=3  LaunchCount=1  
WarmupCount=3 
Method Mean Error StdDev Ratio RatioSD Gen0 Allocated Alloc Ratio
UsingStringNatively 151.8 ns 32.19 1.76 1.00 0.00 0.0153 256 B 1.00
UsingValueObjectAsStruct 184.8 ns 12.19 0.67 1.22 0.02 0.0153 256 B 1.00

There is a tiny amount of performance ov

Issues· 58 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

C#contributions-welcomecsharp-sourcegeneratordddddd-patterns

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 推出的简洁高效系统语言