skip to content
Khalid Abuhakmeh logo Khalid Abuhakmeh

Vogen: Value Objects in C# with a Source Generator

Learn Vogen 8, the C# source generator for validated value objects: install it, validate with From and TryFrom, serialize JSON, and compare alternatives.

8 min read Updated

Correctness is the name of the game in programming. Every bug that comes from passing the wrong string or int to the wrong place is a bug the compiler could have caught if we had given those values real types. Value objects do exactly that.

Vogen is a C# source generator that turns a primitive like string or int into a strongly-typed, validated value object. You write a few lines, and Vogen generates the factory methods, equality, conversions, and serializers, so invalid values can’t sneak into your domain.

Updated November 2026 for Vogen 8.

In this post, we’ll build a small Pac-Man sample to see how Vogen works, what it prevents, and how it compares to the alternatives.

What is a value object?

A value object represents a logical concept but is stored as a .NET primitive such as int, bool, or string. A straightforward example is a birthdate. Most developers define one as a DateTime and hope the variable name clarifies the intent.

DateTime birthDate = new DateTime(1990, 1, 1);

The drawback is that nothing stops anyone from using birthDate incorrectly.

DateTime birthDate = new DateTime(1990, 1, 1);
SetMovieReleaseDate(birthDate);
void SetMovieReleaseDate(DateTime date) { }

The code works, but it probably isn’t what anyone intended. Let’s fix it with value objects.

var birthDate = new BirthDateTime(new (1990, 1, 1));
var movieReleaseDate = new MovieReleaseDateTime(birthDate.Value);
SetMovieReleaseDate(movieReleaseDate);
void SetMovieReleaseDate(MovieReleaseDateTime date) { }
// value objects
public record MovieReleaseDateTime(DateTime Value);
public record BirthDateTime(DateTime Value);

Now the intent is explicit, and passing a BirthDateTime where a MovieReleaseDateTime is expected is a compile error. This can feel ceremonious, which is the gap Vogen fills.

What is Vogen?

Vogen is an open-source NuGet library (Apache 2.0 licensed, free to use) that uses source generators to create value objects from partial struct, class, record struct, or record class types. It generates factory methods, equality, comparison, validation hooks, and serializers.

Add it to a .NET project:

<PackageReference Include="Vogen" Version="8.0.7" />

Or run dotnet add package Vogen. The generic [ValueObject<T>] attribute needs C# 11 (.NET 7 or later by default). On older targets, use [ValueObject(typeof(string))].

How do I create a value object with validation?

I’ll create a PacMan class whose FavoriteGhost must be a valid Ghost. Everyone knows the ghosts are Blinky, Pinky, Inky, and Clyde, so let’s enforce that.

using Vogen;
[ValueObject<string>]
public partial struct Ghost
{
private static readonly HashSet<string> Allowed =
new(["Blinky", "Pinky", "Inky", "Clyde"]);
public static readonly Ghost Blinky = From("Blinky");
public static readonly Ghost Pinky = From("Pinky");
public static readonly Ghost Inky = From("Inky");
public static readonly Ghost Clyde = From("Clyde");
public static IReadOnlyCollection<Ghost> All { get; } = [Blinky, Pinky, Inky, Clyde];
private static string NormalizeInput(string input) =>
string.IsNullOrWhiteSpace(input)
? input
: char.ToUpperInvariant(input.Trim()[0]) + input.Trim()[1..].ToLowerInvariant();
private static Validation Validate(string input) =>
Allowed.Contains(input)
? Validation.Ok
: Validation.Invalid($"Ghost must be one of: {string.Join(", ", Allowed)}");
}

A few things are happening here:

  • From(...) is the generated factory. It runs NormalizeInput first, then Validate.
  • Validate returns Validation.Ok or Validation.Invalid("message").
  • NormalizeInput cleans up the value before validation, so " clyde " becomes "Clyde".
  • The known ghosts are plain static readonly fields built with From.

Notice that Validate checks a separate Allowed set instead of the All collection. Static fields initialize in the order they appear in the file. Blinky = From("Blinky") triggers Validate immediately, and All doesn’t exist yet at that point. Keep the set of allowed values independent, and declare it first.

Also, don’t use new("Blinky") inside the type. In a static field initializer such as public static readonly Ghost F = new("nope");, Vogen 8.0.7 compiles it, and it bypasses both NormalizeInput and Validate. Inside methods, the same new call produces VOG010. Use From everywhere, including inside the type.

Vogen can also declare known instances with [Instance("Blinky", "Blinky")] attributes. The values are trusted and not validated, and the docs now lean toward static fields as shown above.

Here’s the full program:

using System.Text.Json;
using Vogen;
var pacMan = new PacMan { FavoriteGhost = Ghost.Blinky };
foreach (var ghost in Ghost.All)
{
Console.WriteLine(ghost);
}
Console.WriteLine(pacMan);
if (Ghost.TryFrom("Khalid", out var maybeGhost))
Console.WriteLine($"Got {maybeGhost}");
else
Console.WriteLine("Khalid is not a ghost.");
try
{
var aNewGhost = Ghost.From("Khalid");
}
catch (ValueObjectValidationException ex)
{
Console.WriteLine(ex.Message);
}
Console.WriteLine(Ghost.From(" clyde "));
var json = JsonSerializer.Serialize(pacMan);
Console.WriteLine(json);
var back = JsonSerializer.Deserialize<PacMan>(json)!;
Console.WriteLine(back.FavoriteGhost == Ghost.Blinky);
Console.WriteLine(Ghost.Blinky.Equals("Blinky"));
[ValueObject<string>(conversions: Conversions.SystemTextJson)]
public partial struct Ghost
{
private static readonly HashSet<string> Allowed =
new(["Blinky", "Pinky", "Inky", "Clyde"]);
public static readonly Ghost Blinky = From("Blinky");
public static readonly Ghost Pinky = From("Pinky");
public static readonly Ghost Inky = From("Inky");
public static readonly Ghost Clyde = From("Clyde");
public static IReadOnlyCollection<Ghost> All { get; } = [Blinky, Pinky, Inky, Clyde];
private static string NormalizeInput(string input) =>
string.IsNullOrWhiteSpace(input)
? input
: char.ToUpperInvariant(input.Trim()[0]) + input.Trim()[1..].ToLowerInvariant();
private static Validation Validate(string input) =>
Allowed.Contains(input)
? Validation.Ok
: Validation.Invalid($"Ghost must be one of: {string.Join(", ", Allowed)}");
}
public class PacMan
{
public Ghost FavoriteGhost { get; set; }
public override string ToString() => $"Pac Man's favorite ghost is {FavoriteGhost}.";
}

Running it prints:

Blinky
Pinky
Inky
Clyde
Pac Man's favorite ghost is Blinky.
Khalid is not a ghost.
Ghost must be one of: Blinky, Pinky, Inky, Clyde
Clyde
{"FavoriteGhost":"Blinky"}
True
True

Ghost.From("Khalid") throws a ValueObjectValidationException with our message. When invalid input is expected, such as user input, use TryFrom, which returns a bool and an out value instead of throwing. Vogen also generates a TryFrom overload that returns a ValueObjectOrError<Ghost>.

What does Vogen prevent?

Validation only matters if people can’t go around it. Vogen ships analyzers that turn the common escape hatches into compile errors:

var a = new Ghost(); // error VOG010
Ghost b = default; // error VOG009
var c = default(Ghost); // error VOG009
  • VOG010: the type can’t be constructed with new outside the value object.
  • VOG009: the type can’t be constructed with default.
  • VOG008: user-defined constructors are prohibited.

I confirmed all three fire as compile errors with these IDs in Vogen 8.0.7.

That’s the key difference from a hand-written wrapper. The analyzers can’t see everything: an array like new Ghost[3] still holds default structs. Vogen covers that at runtime. Reading .Value on an uninitialized instance throws a ValueObjectValidationException (“Use of uninitialized Value Object”), and ToString() returns [UNINITIALIZED], so a bad value fails loudly instead of flowing through your app.

How do I serialize a value object with System.Text.Json or EF Core?

Pass the serialization formats you need through the conversions parameter:

[ValueObject<string>(conversions: Conversions.SystemTextJson)]
public partial struct Ghost { /* ... */ }

In the program above, JsonSerializer.Serialize(pacMan) produced {"FavoriteGhost":"Blinky"}. The value is written as the underlying primitive. Deserializing runs NormalizeInput and Validate again, so {"FavoriteGhost":"Khalid"} throws a JsonException (“The JSON value could not be converted to Ghost”) with the ValueObjectValidationException as its inner exception.

Combine flags with |, for example Conversions.SystemTextJson | Conversions.EfCoreValueConverter. The EF Core option generates a value converter you register on your model, and it requires the EF Core package in your project. Other options include NewtonsoftJson, DapperTypeHandler, LinqToDbValueConverter, Bson, Orleans, MessagePack, ServiceStackDotText, and XmlSerializable. A TypeConverter is generated by default.

To avoid repeating yourself, set defaults for the whole assembly:

[assembly: VogenDefaults(conversions: Conversions.SystemTextJson | Conversions.TypeConverter)]

Individual value objects can still override the defaults in their own [ValueObject<T>] attribute. Only add Conversions.EfCoreValueConverter to the defaults in projects that reference EF Core, or the generated converter won’t compile.

How does Vogen compare to records, StronglyTypedId, and ValueOf?

Option Source generated Validation Blocks default / new Best for
Vogen Yes Built in (Validate, NormalizeInput) Yes, via analyzers Validated value objects of any primitive
readonly record struct No You write it No, default bypasses your rules Simple wrappers with no invariants
StronglyTypedId Yes Not its focus No Strongly-typed IDs
ValueOf No Optional (override Validate) No Quick, lightweight wrappers

If all you need is OrderId instead of Guid, StronglyTypedId is a great focused tool. If you want invariants enforced at the type level, Vogen is the one I’d reach for. Vogen aims for near-primitive performance, but I haven’t benchmarked it against your workload, so measure if it matters.

FAQ

Is Vogen free, and what license does it use?

Yes. Vogen is open source under the Apache 2.0 license, and you can find the code on GitHub.

Does new inside the value object skip validation?

Sometimes. In a static field initializer, new(...) compiles and bypasses Validate and NormalizeInput. A value object whose Validate rejects everything except "ok" will still happily create new("nope") in public static readonly Ghost F = new("nope");. Inside methods, the analyzer reports VOG010. Use From instead.

How is Vogen different from C# records?

Records give you value equality but no enforced invariants. Anyone can call default(MyRecordStruct) or the constructor with bad data. Vogen generates the value-object plumbing and uses analyzers to keep invalid instances out. See my post on records and the with keyword for how records behave.

Does Vogen work with ASP.NET Core model binding and minimal APIs?

Yes. With the default conversions, a Minimal API handler like app.MapGet("/ghost/{g}", (Ghost g) => ...) binds route and query string values. /ghost/pinky arrives as Pinky because NormalizeInput runs, and /ghost/Khalid fails validation and returns a 400 Bad Request. Add Conversions.SystemTextJson to bind JSON request bodies. Invalid values in a body also return 400.

Which .NET versions does Vogen support?

The generic [ValueObject<T>] attribute requires C# 11, which means .NET 7 or later by default. For earlier targets, use [ValueObject(typeof(string))]. I ran every sample in this post with Vogen 8.0.7 on .NET 10 (SDK 10.0.404).

Conclusion

Value objects constrain inputs logically, improve readability, and make wrong code fail to compile. Vogen removes the boilerplate: you write Validate, and it generates everything else, while its analyzers keep new and default from sneaking in invalid values.

My suggestion is to pick one primitive-heavy part of your codebase, such as an email, a SKU, or a status code, and convert it to a Vogen value object. If you want more C# reference material, check out the C# cheat sheet.

I hope you enjoyed this post. As always, thanks for reading and sharing my posts.

Comments

Related Posts