csharp / expert
Snippet
Domain-Driven Value Types using Readonly Record Structs
Using readonly record structs for domain IDs prevents 'primitive obsession' and ensures type safety. Unlike classes, they are allocated on the stack (improving performance) and provide built-in value-based equality, making them ideal for high-performance domain modeling.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public readonly record struct TransactionId(Guid Value){public static TransactionId New() => new(Guid.NewGuid());public override string ToString() => Value.ToString("D");}public sealed class PaymentProcessor{public void Process(TransactionId id, decimal amount){if (amount <= 0) throw new ArgumentOutOfRangeException(nameof(amount));// Logic processing the unique domain type}}
Breakdown
1
public readonly record struct TransactionId(Guid Value)
Defines an immutable value type with compiler-generated equality and deconstruction.
2
public void Process(TransactionId id, ...)
Enforces domain-specific types in method signatures, preventing the passing of raw GUIDs from other contexts.