Domain models often begin as a single class with a status enum. It is quick, familiar, and deceptively expensive.
A Payment might have a PaymentStatus, an optional failure reason, a nullable settlement timestamp, and perhaps a transaction identifier that is meaningful only after authorization. The compiler sees one object with several independently mutable fields. The business sees a finite set of valid shapes.
That mismatch is where invalid states enter: a failed payment with a settlement timestamp, a pending payment with a decline code, or a completed payment whose receipt was never created.
C# unions and closed classes, being explored in the .NET 11 preview era, point toward a more direct way to model that reality. Instead of using one broad type plus conventions, define a family of permitted cases. Each case owns the data that makes sense for it, and code consuming the family must account for every possibility.
The result is not merely cleaner syntax. It changes where correctness lives: from comments, tests, and runtime checks into the type system.
Preview features and their final syntax can change. Treat the examples below as a design model for union-style programming rather than a promise of final compiler syntax.
The problem with status-shaped objects
Consider a conventional order result:
Nothing prevents callers from constructing this:
Validation can reject that object, but validation is optional and happens after construction. Every consumer must also remember the informal contract: OrderId exists for accepted submissions, DeclineReason is relevant for declined submissions, and RetryAfter applies to temporary failures.
A union describes those alternatives as types rather than as documentation.
The important word is closed. A closed base type says that the set of valid derived cases is deliberately finite. External code cannot quietly add ManualReview, Unknown, or ExperimentalResult and make existing decision logic incomplete without the owning model changing too.
That is the essential distinction between an extensible class hierarchy and a union: inheritance says “others may specialize this”; a union says “these are all the cases.”
Exhaustiveness is the practical payoff
Once a type has a known, finite family of cases, pattern matching becomes a decision table checked by the compiler.
When a new case such as RequiresCustomerAction is introduced, every switch that translates, displays, persists, or otherwise interprets an order submission should become a review point. That compiler pressure is valuable. It turns an easily missed release-note detail into an explicit engineering decision.
This matters most at boundaries:
- translating provider failures into API responses;
- selecting a retry, compensation, or dead-letter action in a worker;
- mapping domain outcomes to persistence records;
- rendering a UI state; and
- publishing integration events.
A default arm can still be appropriate when a boundary intentionally degrades unknown input. Inside core domain logic, however, a catch-all arm often throws away the strongest benefit of a closed model. Prefer exhaustive handling, then let the compiler identify the places affected by a new case.
Closed does not mean behaviourless
A common concern is that union cases create passive data records and push behaviour into giant switch statements. That is a risk, but it is not inherent to the approach.
Put behaviour that belongs to one case on that case. Put behaviour that requires comparing all alternatives in a focused operation over the union.
For example, retry eligibility is intrinsic to a temporary outage:
By contrast, an HTTP translation is an application-boundary concern. It belongs in an endpoint mapper, not in the domain type. The distinction is the same one used in good object-oriented design today; unions simply make alternative-specific data more precise.
Choose cases around meaningful differences
The best union cases are not arbitrary labels. They represent alternatives that differ in valid data, allowed operations, or workflow consequences.
For example, these are usually good candidates:
Authenticated,ChallengeRequired, andRejectedlogin results;Found,NotFound, andForbiddenresource access results;Scheduled,Running,Succeeded,Failed, andCancelledjob states;PercentDiscount,FixedAmountDiscount, andFreeShippingDiscountpromotions.
Conversely, do not turn every enum into a union. If all values share the same data and are used purely as a scalar category—such as a month, country code, or display priority—an enum remains simpler. A union earns its complexity when each alternative has a different shape or semantic contract.
There is also a useful warning sign: if one case accumulates a dozen nullable properties, it may contain several hidden cases. Split it until each variant has a coherent invariant.
Migration without a rewrite
Most established .NET systems cannot replace every status object in one pull request. A safer path is to introduce unions at the seams where correctness is already costly.
Start with a return type that currently uses null, exceptions, and flags to communicate ordinary business outcomes. For example, a service returning Customer? and throwing an exception for access denial can instead return a finite CustomerLookup result.
Then adapt it at the existing boundary:
Keep serialization contracts stable initially. A union is a strong internal model, but public JSON needs an explicit wire representation with a discriminator such as kind. Do not rely on runtime type names as a long-term API contract. Map each domain case to a versioned DTO deliberately, and document how clients should handle future discriminator values.
Persistence needs equal care. Relational storage may use a discriminator column and case-specific nullable columns, separate tables, or a JSON payload depending on query requirements. The union protects in-memory construction; database constraints and migration design still protect stored data.
Design for evolution, not just closure
Closed models are intentionally resistant to uncontrolled extension, but product requirements still change. Adding a case is a source-breaking event for exhaustive consumers, and that is often exactly right inside a single solution. It forces the team to answer: what should happen now?
At public package boundaries, the answer may differ. Consumers outside your deployment cadence cannot always absorb a new case immediately. Consider exposing a stable, intentionally broader contract there, or include an explicit Unknown representation only when forward compatibility is a real requirement. Do not add Unknown merely to silence compiler feedback.
The goal is not to eliminate change. It is to make consequential change visible.
A more truthful model
C# unions and closed classes offer a vocabulary for an idea developers already know: a payment cannot be both accepted and declined, an authorization result is not “mostly successful,” and a workflow state carries obligations as well as a label.
In .NET 11 preview work, the most useful question is not “where can I replace an enum?” Ask instead: “where does my code currently allow combinations the business says can never happen?”
Those are the places where a closed family of cases can turn fragile conventions into compiler-checked design. The code becomes more explicit, change becomes more visible, and invalid states have fewer places to hide.
No comments yet. Be the first to share your thoughts!