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.
Join the conversation! Your thoughts help the community grow.