Records in Domain-Driven Design
Model value objects, DTOs, and domain events as records to enforce immutability and improve code clarity.
DDD and Value Objects
In Domain-Driven Design (DDD), a Value Object is defined by its properties, not identity. Two Money(100, "USD") values are interchangeable. Records are the perfect C# representation for value objects.
Value Objects as Records
Model domain value objects as records. Their structural equality, immutability, and concise syntax align perfectly with DDD principles.
// Value objects — defined by their values, not identity
public record Money(decimal Amount, string Currency);
public record Email(string Value);
public record PhoneNumber(string CountryCode, string Number);
public record Address(string Street, string City, string Country, string PostalCode);
// Two Money objects with same values are equal:
var price = new Money(99.99m, "USD");
var same = new Money(99.99m, "USD");
Console.WriteLine(price == same); // TrueAll lessons in this course
- Record Types: Basics & Syntax
- Immutability with init & with
- Value Equality & Deconstruction
- Records in Domain-Driven Design