Explains primitive obsession, the bugs it allows (swapped IDs, unvalidated strings, currency-less money), and how to fix it with readonly record struct IDs, validated value objects and records, including EF Core value converters, JSON serialisation and where to validate.
Primitive obsession is representing domain concepts with raw types: Guid for every ID, string for email and ABN, decimal for money. The compiler can't tell a customerId from an orderId, so swapped arguments compile, and every caller re-validates (or forgets to).
The fix is small types that carry meaning:
readonly record struct OrderId(Guid Value): no allocation, value equality, swaps become compile errors.Email, Abn, Money validate once when created, so an invalid instance can't exist.The costs are mapping (EF Core value converters or ComplexProperty, JSON converters, model binding) and some ceremony. I use them where mix-ups are likely or rules are real, not for every int.
"Primitive obsession is using built-in types for things that have meaning and rules in the domain. An order ID is a
Guid, a customer ID is aGuid, soRefund(Guid orderId, Guid customerId)will happily accept them the wrong way round. An email address is astring, so nothing stops""or"n/a"reaching the mail sender, and the validation is copy-pasted into every handler. Money is adecimal, so adding AUD to NZD compiles. The smell is the missing type, and the symptoms are duplicated validation, parameter mix-ups and comments like// in cents.In modern C# the fix is cheap. For IDs I use
readonly record struct OrderId(Guid Value): it's a value type, so no allocation, records give value equality andToStringfor free, and passing anOrderIdwhere aCustomerIdis expected is now a compile error. For concepts with rules I use a value object with a factory, for exampleEmail.Create(string)returning a result or throwing, so validation happens once at the boundary and the rest of the code can trust the type.Moneycarries amount and currency and implements its own arithmetic and rounding. For example, at [company] we [found a refund applied to the wrong order because two Guids were swapped]; after introducing typed IDs the compiler found [N] more call sites with the same risk.The mistake I see is going all-in or nothing. These types need plumbing: EF Core value converters or
ComplexProperty, JSON converters, route and query binding viaIParsable<T>, and Swagger schemas. I use them for IDs that get mixed up, money, and anything with validation rules like ABN or email. Aquantitythat is just anintwith a range check may not be worth a type."
| Primitive | Domain concept | Better type | What it buys you |
|---|---|---|---|
Guid |
OrderId, CustomerId |
readonly record struct |
Swaps are compile errors |
string |
Email, ABN, postcode | Value object with factory | Validated once; normalised (trim, lower-case) |
decimal |
Money | Money(decimal Amount, Currency Currency) |
Currency safety, one rounding rule |
int + comment |
Cents, minutes | Cents, TimeSpan |
Units in the type |
| Several primitives together | Address (street, suburb, state, postcode) | Record | Removes the data clump too |
| Technique | Use when | Avoid when |
|---|---|---|
| Typed ID (record struct) | IDs of different entities appear in the same signatures | Single-entity microservice with one ID type |
| Value object (class or record with factory) | Rules and normalisation exist | No rules, never confused with other values |
| Source generator (Vogen, StronglyTypedId) | Dozens of IDs; want converters generated | One or two types: hand-written is clearer |
In an invoicing API with [30] entities, typed IDs typically surface a handful of real swapped-argument bugs at compile time on day one. Moving ABN validation into an Abn value object removes the check from every handler that previously repeated it, and the per-request cost is negligible because record structs don't allocate.
Checks that the candidate can turn a smell into concrete C# types and understands the real-world plumbing and costs.
Green flags
readonly record struct for IDs and explains why (no allocation, value equality)Red flags
A type is a set of allowed values plus allowed operations. string allows any text and every string operation; an email address allows a tiny subset and almost none of those operations. When you use string, every function that receives one must either re-check it or trust that someone upstream did. Value objects move that knowledge into the type system: parse, don't validate.
HTTP JSON "customerEmail": " [email protected] "
|
v boundary: Email.Create(raw) -> validate + normalise once
Email("[email protected]")
|
v domain + infrastructure trust the type; no more checks
readonly record struct OrderId(Guid Value): value type, 16 bytes, stack or inline, no GC pressure, compiler-generated Equals, GetHashCode, ==, ToString. default(OrderId) is Guid.Empty, so guard against it.sealed record Email: reference type, can enforce invariants through a private constructor and factory (structs always have a public parameterless default).Rule of thumb: IDs as record structs, validated concepts as sealed records or classes with a private constructor.
EF Core. Two options:
HasConversion(id => id.Value, v => new OrderId(v)), or for every property of a type at once in ConfigureConventions with configurationBuilder.Properties<OrderId>().HaveConversion<OrderIdConverter>(). Single-column values.ComplexProperty, EF Core 8+, improved in later versions): multi-column value objects like Money or Address mapped into the owner's table without identity.Watch out: some LINQ translations on converted properties are limited (e.g. calling methods on .Value inside queries), and key generation for typed keys needs ValueGeneratedOnAdd handling or client-side Guid.CreateVersion7().
System.Text.Json. Write a JsonConverter<OrderId> or let a generator produce one, so the JSON stays "orderId": "3f2..." rather than {"value": ...}.
ASP.NET Core binding. Implement IParsable<OrderId> and minimal APIs and MVC bind route and query values directly: app.MapGet("/orders/{id}", (OrderId id) => ...).
User input should fail with a 400 and a helpful message, not an exception deep in the domain. Two common shapes:
TryCreate(string, out Email?) or a Result<Email> at the boundary, mapped to ValidationProblem.Email.Create that throws only for programming errors.Guid customerId parameters creeping back(Guid orderId, Guid customerId) to typed IDs and count the compile errors that reveal call sites.[MemoryDiagnoser]) a dictionary lookup keyed by Guid versus OrderId; confirm zero extra allocation.Money with ComplexProperty and inspect the generated table with dotnet ef migrations script.IParsable<OrderId> and bind it in a minimal API route.Before and after for an invoice refund: typed IDs, a validated value object and money with currency.
// Before: primitives everywhere
namespace Billing.Before;
public class RefundService(BillingDbContext db)
{
// Swapping the two Guids compiles; email and amount are unchecked
public async Task Refund(Guid invoiceId, Guid customerId, decimal amount, string email, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(email) || !email.Contains('@'))
throw new ArgumentException("Bad email"); // repeated in 6 other handlers
var invoice = await db.Invoices.SingleAsync(i => i.Id == invoiceId && i.CustomerId == customerId, ct);
invoice.Refunded += amount; // which currency?
await db.SaveChangesAsync(ct);
}
}
// After: types carry meaning and rules
namespace Billing.After;
using System.Diagnostics.CodeAnalysis;
public readonly record struct InvoiceId(Guid Value) : IParsable<InvoiceId>
{
public static InvoiceId New() => new(Guid.CreateVersion7());
public static InvoiceId Parse(string s, IFormatProvider? provider) => new(Guid.Parse(s, provider));
public static bool TryParse([NotNullWhen(true)] string? s, IFormatProvider? provider, out InvoiceId result)
{
var ok = Guid.TryParse(s, provider, out var g);
result = new InvoiceId(g);
return ok;
}
}
public readonly record struct CustomerId(Guid Value);
public sealed record Email
{
public string Value { get; }
private Email(string value) => Value = value;
public static bool TryCreate(string? raw, [NotNullWhen(true)] out Email? email)
{
var trimmed = raw?.Trim().ToLowerInvariant();
email = trimmed is { Length: > 3 } && trimmed.IndexOf('@') > 0 ? new Email(trimmed) : null;
return email is not null;
}
}
public enum Currency { Aud, Nzd }
public sealed record Money(decimal Amount, Currency Currency)
{
public static Money operator +(Money a, Money b) =>
a.Currency == b.Currency
? a with { Amount = a.Amount + b.Amount }
: throw new InvalidOperationException($"Cannot add {a.Currency} to {b.Currency}");
}
public sealed record RefundRequest(InvoiceId Invoice, CustomerId Customer, Money Amount, Email NotifyEmail);
// EF Core: map every typed ID once, and Money as a complex type
protected override void ConfigureConventions(ModelConfigurationBuilder builder)
{
builder.Properties<InvoiceId>().HaveConversion<InvoiceIdConverter>();
builder.Properties<CustomerId>().HaveConversion<CustomerIdConverter>();
}
protected override void OnModelCreating(ModelBuilder modelBuilder) =>
modelBuilder.Entity<Invoice>().ComplexProperty(i => i.Refunded);
public sealed class InvoiceIdConverter() : ValueConverter<InvoiceId, Guid>(id => id.Value, v => new InvoiceId(v));
public sealed class CustomerIdConverter() : ValueConverter<CustomerId, Guid>(id => id.Value, v => new CustomerId(v));
Email changed to ""), and equality is by reference. Instead: Immutable record or record struct with a validating factory.default and new() bypass validation. Instead: Use a sealed record with a private constructor for validated values; keep structs for IDs.TryCreate/Result at the boundary, mapped to ValidationProblem.{"value":"..."} and breaks clients. Instead: Add JsonConverters (or a generator) and contract tests.o.Id.Value == x against converted properties. Why it is wrong: EF Core may fail to translate it. Instead: Compare typed values directly: o.Id == invoiceId.decimal with currency in a separate parameter. Why it is wrong: Arithmetic across currencies still compiles. Instead: A Money type whose operators check currency and own rounding.The senior view is that primitive obsession is a type-design problem that also fixes a validation-duplication problem: once Abn exists, the eleven-digit checksum lives in one place and the Privacy-relevant fields are easy to find and treat carefully (for example, an Email or TaxFileNumber type can override ToString to redact in logs). That is a real benefit under the Privacy Act 1988 when you need to show where personal information flows. The types also document the domain: a new developer reading Refund(InvoiceId, Money) learns more than from Refund(Guid, decimal).
I decide by context: how many entity types share signatures, how rich the rules are, and how much the domain is expected to grow. A small CRUD service with one ID type gains little; a billing domain with thirty entities and money in several currencies gains a lot. Performance is rarely the issue: a readonly record struct around a Guid is the same 16 bytes with no allocation, so even hot paths are unaffected; validated value objects that are classes add one small allocation each, which only matters in very high-throughput loops and can be measured with BenchmarkDotNet. On a big codebase I introduce them per bounded context, starting where bugs have actually happened, and add an analyser or review checklist so new raw Guid parameters don't creep back.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Hand-written record struct IDs | Up to ~10 ID types | A few lines plus converters each | Dozens of IDs: boilerplate grows |
| Source generator (Vogen, StronglyTypedId) | Many IDs, want generated EF/JSON converters | A dependency and generated code to understand | Team unfamiliar with generators, few types |
| Value object with factory | Rules, normalisation, sensitive data | Boundary mapping, error handling | No rules and no confusion risk |
| Keep the primitive | Local, short-lived values | None | Values crossing layers or APIs |
A value converter tells EF Core how to turn a .NET value into a column value and back, configured with HasConversion.
HasConversion<string>() plus HasMaxLength(20). Readable in SQL and safe when enum members are reordered.readonly record struct OrderId(Guid Value) with a ValueConverter<OrderId, Guid>, applied model-wide in ConfigureConventions. The compiler stops you passing a CustomerId where an OrderId belongs.You need a value comparer when the converted type is mutable (say List<string> stored as JSON), or edits go unnoticed. In LINQ, compare the whole converted value (o.Id == id); o.Id.Value usually doesn't translate. The trade-off: richer domain types versus a few query restrictions.
An entity has an identity that stays the same while its attributes change: customer #42 is the same customer after moving house. Two entities are equal if their Ids match. A value object has no identity; it is defined by its values, so two Money(100, "AUD") instances are equal. Value objects should be immutable and validate themselves on creation, so an invalid one can never exist.
In C#, a record or readonly record struct gives value equality for free, but the generated equality compares collections by reference, so a value object holding a list needs ImmutableArray<T> and a SequenceEqual-based Equals. In EF Core 10, complex types (ComplexProperty) are the preferred mapping: value semantics, no hidden key, and now struct, optional and JSON-mapped complex types (including complex collections). Use a value converter for single-value types like EmailAddress. The trade-off: more types, far fewer invalid states.
How to tell it (STAR)
**S:** At [company] a refund was applied to the wrong invoice because a caller passed `customerId` and `invoiceId` in the wrong order; both were `Guid`s, so it compiled. **T:** I owned the fix and wanted to make this class of bug impossible. **A:** After reversing the refund and fixing the call site, I introduced strongly typed IDs as record structs, with EF Core converters registered once and JSON converters so the API contract didn't change. I rolled it out module by module and added an analyser rule against multiple raw Guid parameters. **R:** The compiler found [4] more risky call sites on the first day, and we've had [no] ID mix-up defects since; the change added [no measurable] latency.
Last updated 23 Nov 2026.