Application code often has to return more than one possible result.
A method might return a successful response, a validation failure, a not-found result, or an authorization error. In traditional C# code, developers commonly represent these outcomes using exceptions, nullable values, tuples, inheritance, or large result classes.
Union types provide another way to model this situation.
The basic idea is simple: a value can be one of several explicitly defined types.
Instead of writing a method that returns something vague like object, application code can describe its valid outcomes directly.
For example:
public OrderResult CreateOrder(CreateOrderRequest request)
{
// Success, validation failure, or duplicate order
}A union-style result can make those possibilities visible in the API contract.
This is particularly useful in application services, domain logic, parsers, validation pipelines, and APIs where multiple outcomes are expected rather than exceptional.
What Is a Union Type?
A union type represents a value that can belong to one of several types.
Conceptually:
Result
├── Success
├── ValidationError
└── NotFoundOnly one of these alternatives is present at a time.
This is different from a normal inheritance hierarchy where the base type may be used to represent many possible objects.
A union is specifically about expressing a finite set of alternatives.
For example:
OrderResult result;could represent:
OrderCreated
ValidationFailed
OrderNotFoundThe consumer then handles each possible case.
Why Union Types Matter in Application Code
Consider a traditional service method:
public async Task<Order?> GetOrderAsync(int id)
{
return await repository.FindAsync(id);
}The caller receives either an order or null.
That does not tell the caller why the order is unavailable.
Maybe the order does not exist.
Maybe the user is not authorized.
Maybe the request was invalid.
Those are different situations, but the return type does not communicate that distinction.
A richer result could model the outcomes explicitly:
GetOrderResult
|
+-- OrderFound
+-- OrderNotFound
+-- AccessDeniedNow the API communicates more information without relying on exceptions for normal control flow.
Union Types and Result Modeling
A useful application pattern is to create a result hierarchy.
public abstract record OrderResult;
public sealed record OrderCreated(Order Order)
: OrderResult;
public sealed record ValidationFailed(
IReadOnlyList<string> Errors)
: OrderResult;
public sealed record OrderNotFound(int OrderId)
: OrderResult;The service can return:
public async Task<OrderResult> CreateOrderAsync(
CreateOrderRequest request)
{
if (request.Items.Count == 0)
{
return new ValidationFailed(
["An order must contain at least one item."]);
}
var order = await repository.CreateAsync(request);
return new OrderCreated(order);
}The result type now tells callers that there are multiple expected outcomes.
This pattern is especially useful when the application needs to distinguish business outcomes from unexpected failures.
Handling Each Result
The caller can inspect the result type:
var result = await service.CreateOrderAsync(request);
switch (result)
{
case OrderCreated created:
return Results.Ok(created.Order);
case ValidationFailed validation:
return Results.BadRequest(validation.Errors);
case OrderNotFound notFound:
return Results.NotFound(notFound.OrderId);
default:
throw new InvalidOperationException(
"Unsupported order result.");
}The important part is that each case represents a known business outcome.
Unexpected failures can still use exceptions.
Union Types Versus Exceptions
Exceptions are appropriate when something exceptional happens.
For example:
throw new DatabaseUnavailableException();A validation failure, however, may be an expected outcome:
Invalid email
Invalid product ID
Missing order item
Duplicate requestThrowing exceptions for every expected business result can make the control flow harder to understand.
A union-style result separates the two concepts:
Expected outcome
-> Result type
Unexpected failure
-> ExceptionThis distinction is valuable in service and domain code.
Union Types Versus Nullable Values
Nullable values work well when there are only two meaningful states:
Product?The meaning is straightforward:
Product
nullBut the model becomes ambiguous when more states are required.
For example:
Product
NotFound
AccessDenied
InvalidRequestA nullable return value cannot represent all these states cleanly.
A union-style model makes the alternatives explicit.
Union Types Versus Tuples
Tuples are useful for returning multiple related values:
public (bool Success, string? Error) Validate()However, the tuple does not create a strong semantic type.
A result such as:
(bool Success, string? Error)allows combinations that may not make sense.
For example:
(true, "Something went wrong")The type does not prevent that state.
A discriminated result can make invalid combinations harder to represent:
Success
ErrorEach alternative carries only the data appropriate for that case.
Modeling API Results
Union-style result models work particularly well at API boundaries.
Consider an endpoint that creates a customer:
POST /customersPossible outcomes might be:
CustomerCreated
ValidationFailed
EmailAlreadyExistsInstead of returning an arbitrary object, the application can define those outcomes explicitly.
public abstract record CreateCustomerResult;
public sealed record CustomerCreated(
Customer Customer) : CreateCustomerResult;
public sealed record ValidationFailed(
IReadOnlyList<string> Errors) : CreateCustomerResult;
public sealed record EmailAlreadyExists(
string Email) : CreateCustomerResult;The API layer can then map each case to the appropriate HTTP response.
var result = await service.CreateAsync(request);
return result switch
{
CustomerCreated created =>
Results.Created(
$"/customers/{created.Customer.Id}",
created.Customer),
ValidationFailed failed =>
Results.BadRequest(failed.Errors),
EmailAlreadyExists duplicate =>
Results.Conflict(
new { duplicate.Email }),
_ => Results.StatusCode(500)
};The business service does not need to know anything about HTTP status codes.
That keeps application and transport concerns separate.
Exhaustive Handling Is Important
The biggest advantage of union-style modeling appears when all possible cases must be handled.
Suppose a result contains:
Success
NotFound
ValidationFailedThe consuming code should handle those alternatives intentionally.
With a traditional object return type:
object resultthe compiler cannot tell you what types are valid.
With a constrained hierarchy, the possible types are documented in the model.
As C# evolves its support for closed type hierarchies and union-like language features, the goal is to make these finite alternatives easier for both the compiler and developers to reason about.
Use Union Types at the Right Boundary
Not every method needs a union result.
For example, this method is perfectly reasonable:
public decimal CalculateTotal(Order order)
{
return order.Items.Sum(x => x.Price);
}There is no meaningful set of alternative business outcomes.
A union becomes more useful when the method has multiple expected states:
Parse
Validate
Authorize
Create
Update
ProcessA useful rule is:
One meaningful result
-> Return the result directly
Multiple expected outcomes
-> Consider a union-style result
Unexpected failure
-> ExceptionThis keeps simple methods simple.
Union Types in Domain Logic
Domain operations are another good use case.
Imagine an account transfer:
TransferResult
|
+-- TransferCompleted
+-- InsufficientFunds
+-- AccountBlocked
+-- InvalidRecipientThe application can model these states directly:
public abstract record TransferResult;
public sealed record TransferCompleted(
decimal Amount) : TransferResult;
public sealed record InsufficientFunds(
decimal Available) : TransferResult;
public sealed record AccountBlocked : TransferResult;
public sealed record InvalidRecipient(
string AccountId) : TransferResult;The domain service can then return:
public TransferResult Transfer(
Account source,
Account destination,
decimal amount)
{
if (source.IsBlocked)
return new AccountBlocked();
if (amount > source.Balance)
return new InsufficientFunds(source.Balance);
if (!destination.IsActive)
return new InvalidRecipient(destination.Id);
source.Debit(amount);
destination.Credit(amount);
return new TransferCompleted(amount);
}This is easier to reason about than returning a Boolean and relying on a separate error message.
Keep the Union Small
A common mistake is creating a result with too many alternatives.
For example:
Success
ValidationError
NotFound
Unauthorized
Forbidden
DatabaseError
NetworkError
Timeout
SerializationError
ConfigurationError
UnknownError
...At this point, the result type has become difficult to understand.
Separate expected business outcomes from infrastructure failures.
For example:
Business Result
-> Success
-> ValidationFailed
-> NotFoundInfrastructure failures can remain exceptions or be handled by a dedicated reliability layer.
The exact boundary depends on the application architecture, but the goal is to keep the union focused.
Union Types and Pattern Matching
Pattern matching makes union-style models particularly readable.
return result switch
{
OrderCreated created =>
Results.Ok(created.Order),
ValidationFailed failed =>
Results.BadRequest(failed.Errors),
OrderNotFound notFound =>
Results.NotFound(notFound.OrderId),
_ => Results.StatusCode(500)
};This style keeps the mapping logic close to the API boundary.
It also avoids long chains of:
if (...)
{
}
else if (...)
{
}
else if (...)
{
}Pattern matching is one of the natural companions to union-style application design.
Common Mistakes
Returning object
Avoid:
public object Process()The caller has no clear contract describing what the method can return.
Returning null for multiple conditions
Avoid using null to represent not found, unauthorized, invalid, and failed states.
Using exceptions for normal business outcomes
A predictable validation failure usually does not need an exception.
Creating oversized result types
A union should represent a focused set of related outcomes.
Mixing HTTP concerns into domain results
Avoid returning BadRequest, NotFound, or IResult directly from domain services.
Keep HTTP mapping at the API boundary.
Ignoring future cases
When adding a new result alternative, review every consumer that handles the existing cases.
Best Practices
Define a small and meaningful set of alternatives.
Use descriptive names for each result type.
Keep transport concerns outside the domain layer.
Use pattern matching when converting results to API responses.
Use exceptions for genuinely unexpected failures.
Keep generated or infrastructure-specific types out of the core domain model.
Document compatibility expectations when the result is part of a public API.
Add tests for every expected result case.
Comparison
Approach | Best For | Main Limitation |
|---|---|---|
Nullable value | Simple success/not-found result | Cannot represent many states |
Tuple | Small groups of related values | Weak semantic contract |
Exception | Unexpected failures | Poor fit for normal control flow |
Boolean | Simple yes/no operation | Loses failure information |
Result hierarchy | Multiple expected outcomes | Requires explicit result modeling |
Union type | Closed set of alternatives | Needs careful case handling |
Testing Union-Style Results
Each expected outcome should have a test.
[Fact]
public async Task CreateOrder_ReturnsValidationFailure_WhenNoItemsExist()
{
var request = new CreateOrderRequest
{
Items = []
};
var result = await service.CreateOrderAsync(request);
Assert.IsType<ValidationFailed>(result);
}Test the successful case separately:
[Fact]
public async Task CreateOrder_ReturnsCreatedOrder_WhenRequestIsValid()
{
var request = CreateValidRequest();
var result = await service.CreateOrderAsync(request);
var created = Assert.IsType<OrderCreated>(result);
Assert.NotEqual(0, created.Order.Id);
}Testing each alternative ensures that the result contract remains useful as the application changes.
Advantages
Union-style modeling provides several practical benefits:
Advantage | Description |
|---|---|
Explicit contracts | Valid outcomes are visible in the type design |
Better control flow | Expected outcomes do not require exceptions |
Stronger APIs | Callers know what they need to handle |
Better domain modeling | Business states can be represented directly |
Clear pattern matching | Result handling becomes easier to read |
Improved testing | Each expected case can be tested independently |
Disadvantages and Considerations
Consideration | Impact |
|---|---|
More types | Simple operations can become unnecessarily verbose |
Case management | Consumers need to handle each meaningful alternative |
API evolution | Adding cases may require changes in consumers |
Learning curve | Developers need familiarity with pattern matching and result modeling |
Overuse | Using unions everywhere can make simple code complicated |
The goal is not to replace every return type with a union. The goal is to use explicit alternatives where they improve the design.
Summary
Union types are useful when an operation has a small, well-defined set of expected outcomes.
Instead of hiding those states behind null, Boolean values, tuples, or exceptions, application code can model them directly:
Operation
|
+-- Success
+-- ValidationFailed
+-- NotFoundThat makes the contract easier to understand and gives consuming code a clear way to handle each case.
In real ASP.NET Core applications, union-style results are particularly useful at service boundaries and API mapping layers. The domain service can return business outcomes while the API layer converts those outcomes into HTTP responses.
The most important principle is to keep the model focused. Use explicit alternatives when they represent meaningful expected states, and continue using normal return values and exceptions when they are a better fit.

Join the conversation! Your thoughts help the community grow.