Yes, C# 15 union types can replace the Result pattern.
A generic union Result<T>(T, Error) works like the Result class, and a validation decorator still works with it.
To have the compiler catch a new failure, give each failure its own type in a union and wrap it in a generic Outcome<T, TError>.
Most agents treat memory as a bolt-on with a vector store for retrieval, a chat history table beside it, and whatever extraction the team can maintain. This holds up for a demo, but falls short when asked who owns the memory or how to manage what the agent learned. A unified memory core builds memory into the database from the start. Read the breakdown and try the quickstart notebooks.
Run your coding agents inside Rider: Rider 2026.3 ships with JetBrains Air. Run Claude Agent, Codex, Copilot or Junie in parallel, see which session needs your input, and review every diff with Rider's debugger and tests. Junie Lite is free for a limited time. Try Air in Rider.
I've returned expected failures with the Result pattern for years.
Instead of throwing an exception, a method returns an object that holds either a value or an Error.
In May, I gave you a quick tour of union types while they were still in preview. Now they've shipped with C# 15 and .NET 11.
So I took one of my use cases and rewrote it with a generic union. Then I added a new failure to see what the compiler catches.
The Use Case With a Result
The use case reserves an apartment for a range of dates. The command carries the apartment and the two dates:
public sealed record ReserveBooking(Guid ApartmentId, DateOnly Start, DateOnly End);
It can fail in two ways: the apartment doesn't exist, or the dates are already taken.
With the Result pattern, each failure is an Error.
An Error has a Code that identifies the failure and a Description for humans.
The codes are constants, and the errors live in static classes, one per entity, so every handler reuses the same instances:
public sealed record Error(string Code, string Description);
public static class ErrorCodes
{
public const string ApartmentNotFound = "Apartments.NotFound";
public const string Overlap = "Bookings.Overlap";
}
public static class ApartmentErrors
{
public static readonly Error NotFound = new(
ErrorCodes.ApartmentNotFound, "The apartment was not found");
}
public static class BookingErrors
{
public static readonly Error Overlap = new(
ErrorCodes.Overlap, "The apartment is already booked for these dates");
}
The handler returns a Result<Guid>.
It's the Result class from the Result pattern article: it holds either the new booking's id or an Error, and IsSuccess tells you which one.
public async Task<Result<Guid>> Handle(ReserveBooking command)
{
Apartment? apartment = await store.GetApartmentAsync(command.ApartmentId);
if (apartment is null)
{
// A failure is wrapped in a Result.
return Result.Failure<Guid>(ApartmentErrors.NotFound);
}
if (await store.IsOverlappingAsync(apartment, command.Start, command.End))
{
return Result.Failure<Guid>(BookingErrors.Overlap);
}
var booking = Booking.Create(apartment, command.Start, command.End);
store.Add(booking);
// An implicit conversion turns the Guid into a successful Result<Guid>.
return booking.Id;
}
A Minimal API endpoint calls the handler and turns the result into an HTTP response.
On success it returns 201 Created.
On failure it maps each error code to a status code:
app.MapPost("/bookings", async (ReserveBooking command, ReserveBookingHandler handler) =>
{
Result<Guid> result = await handler.Handle(command);
if (result.IsSuccess)
{
return Results.Created($"/bookings/{result.Value}", result.Value);
}
// Match the error code against the known constants.
return result.Error.Code switch
{
ErrorCodes.ApartmentNotFound => Results.NotFound(result.Error),
ErrorCodes.Overlap => Results.Conflict(result.Error),
// Any other code
_ => Results.Problem(result.Error.Description)
};
});
Code is a string, and a string can hold any value.
So the switch needs the _ arm, and Results.Problem turns a code the endpoint doesn't know into a 500.
Keep that _ arm in mind.
It's where a new failure ends up later.
The Result Pattern as a Generic Union
A union is a type that holds exactly one value from a fixed list of types.
Those types are its case types.
You declare a union with the union keyword and list the case types in parentheses.
Result<T> is generic, and a union can be generic too:
// Holds either a T (the success value) or an Error (the failure).
public union Result<T>(T, Error);
For Result<Guid>, the case types are Guid and Error.
Error is the same record as before, with its code and description.
There's no IsSuccess flag: the type of the value inside tells you whether the call succeeded.
The compiler generates a conversion from each case type to the union.
So the handler returns the Error or the Guid as it is, and Result.Failure<Guid>(...) goes away:
public async Task<Result<Guid>> Handle(ReserveBooking command)
{
Apartment? apartment = await store.GetApartmentAsync(command.ApartmentId);
if (apartment is null)
{
// Error converts to Result<Guid>.
return ApartmentErrors.NotFound;
}
if (await store.IsOverlappingAsync(apartment, command.Start, command.End))
{
return BookingErrors.Overlap;
}
var booking = Booking.Create(apartment, command.Start, command.End);
store.Add(booking);
// Guid converts to Result<Guid>.
return booking.Id;
}
The endpoint reads the result with one switch expression.
Each arm is a pattern that checks the type of the value inside the union:
app.MapPost("/bookings", async (ReserveBooking command, ReserveBookingHandler handler) =>
{
Result<Guid> result = await handler.Handle(command);
return result switch
{
// The union holds a Guid: name it id.
Guid id => Results.Created($"/bookings/{id}", id),
// The union holds an Error with this code.
Error { Code: ErrorCodes.ApartmentNotFound } error => Results.NotFound(error),
Error { Code: ErrorCodes.Overlap } error => Results.Conflict(error),
// The union holds any other Error.
Error error => Results.Problem(error.Description)
};
});
Error { Code: ErrorCodes.Overlap } is a property pattern.
It matches an Error whose Code equals that constant.
A pattern can only compare against a compile-time constant, which is one more reason to keep the codes in const fields.
There's no IsSuccess check, and no Value property that throws when you read it on a failure.
Don't return the union itself from the endpoint.
ASP.NET Core 11 serializes the case it holds and returns 200 OK, even for an Error.
The Decorator Still Works
In my CQRS setup without MediatR, every command handler implements one interface:
public interface IHandler<TCommand, TResponse>
{
Task<TResponse> Handle(TCommand command);
}
A validation decorator implements the same interface and wraps another handler.
It checks the command first and calls the inner handler only when the command is valid.
The validate function returns an Error for an invalid command and null for a valid one.
One decorator covers every handler that returns a Result<T>:
public sealed class ValidationDecorator<TCommand, T>(
IHandler<TCommand, Result<T>> inner,
Func<TCommand, Error?> validate) : IHandler<TCommand, Result<T>>
{
public async Task<Result<T>> Handle(TCommand command)
{
Error? error = validate(command);
if (error is not null)
{
return error; // Error converts to Result<T> for any T.
}
return await inner.Handle(command);
}
}
The decorator doesn't know what T is, and it doesn't need to.
An Error converts to Result<Guid>, Result<Order>, or any other Result<T>.
A union stores its case in an object, so the Guid in Result<Guid> gets boxed.
It still beat the Result class in my union vs Result benchmarks.
Add a Failure Case
Now each apartment gets a minimum stay, and a shorter booking has to fail.
The new error needs the minimum in its description.
A static field can't take a parameter, so StayTooShort is a method that builds a new Error each time:
public static class ErrorCodes
{
// ApartmentNotFound and Overlap as before
public const string StayTooShort = "Bookings.StayTooShort";
}
public static class BookingErrors
{
// Overlap as before
public static Error StayTooShort(int minimumNights) => new(
ErrorCodes.StayTooShort,
$"The stay is shorter than the minimum of {minimumNights} nights");
}
BookingErrors.StayTooShort(2) returns an Error with the code Bookings.StayTooShort and the description "The stay is shorter than the minimum of 2 nights".
The handler counts the nights and passes the apartment's minimum to that method:
// DayNumber counts days since January 1, 0001, so the difference is the number of nights.
if (command.End.DayNumber - command.Start.DayNumber < apartment.MinimumNights)
{
return BookingErrors.StayTooShort(apartment.MinimumNights);
}
I added the check to the handler and left the endpoint alone. The build passes with 0 warnings, and the one-night booking returns a 500.
The compiler does check this switch.
If you delete the last Error error arm, the build reports CS8509, because an Error with any other code wouldn't match anything.
But the compiler can't know which codes exist, because a code is just a string.
So it makes you keep a catch-all arm, and that arm is where Bookings.StayTooShort lands.
It's the same _ arm from the Result version, with a different syntax.
Give Each Failure a Type
The compiler can catch a missing failure only if each failure is its own type. So I turned each failure into a record. A record can carry the data the caller needs, like the apartment id or the dates, instead of a description string. Then I listed the records in a union of their own:
public sealed record ApartmentNotFound(Guid ApartmentId);
public sealed record Overlap(DateOnly Start, DateOnly End);
// Every way this use case can fail, and nothing else.
public union ReserveBookingError(ApartmentNotFound, Overlap);
I could put the success case in the same union and return that from the handler.
But then every handler returns its own union, and the decorator only sees a type parameter, its TResponse.
There's no conversion from a failure record to TResponse, so return failure; fails with error CS0029.
The fix is the same trick as Result<T>: a generic union the decorator can build for any handler.
This one has three case types:
public sealed record BookingReserved(Guid BookingId);
// The failure the validation decorator returns, shared by every handler.
public sealed record ValidationFailed(string Message);
// T: the success. TError: the use case's own failures.
public union Outcome<T, TError>(T, TError, ValidationFailed);
The handler returns Outcome<BookingReserved, ReserveBookingError>.
A BookingReserved converts to it directly.
A failure needs a cast:
if (await store.IsOverlappingAsync(apartment, command.Start, command.End))
{
// The cast makes it a ReserveBookingError, which converts to the Outcome.
return (ReserveBookingError)new Overlap(command.Start, command.End);
}
Overlap converts to ReserveBookingError, and ReserveBookingError converts to the Outcome.
C# doesn't chain two conversions like these on its own, so without the cast the build fails with CS0029.
The decorator is the one from before, with ValidationFailed in place of Error.
It implements IHandler<TCommand, Outcome<T, TError>>, and return failure; compiles because a ValidationFailed converts to any Outcome<T, TError>.
The endpoint needs a switch inside a switch:
app.MapPost("/bookings", async (ReserveBooking command, ReserveBookingHandler handler) =>
{
Outcome<BookingReserved, ReserveBookingError> outcome = await handler.Handle(command);
return outcome switch
{
BookingReserved reserved => Results.Created($"/bookings/{reserved.BookingId}", reserved.BookingId),
// The use case's failures: one arm per record.
ReserveBookingError error => error switch
{
ApartmentNotFound notFound => Results.NotFound(notFound),
Overlap overlap => Results.Conflict(overlap)
},
ValidationFailed failed => Results.BadRequest(failed)
};
});
The outer switch handles the three case types of the Outcome.
The inner one handles the records inside ReserveBookingError.
A pattern on the outer switch can't reach into the inner union (that's error CS8121), so you need both.
Neither switch has a _ arm, and that's what lets the compiler help.
Add the Failure Again
Back to the minimum stay.
This time, StayTooShort is a record in the error union:
public sealed record StayTooShort(int MinimumNights);
public union ReserveBookingError(ApartmentNotFound, Overlap, StayTooShort);
The handler returns it with the same cast:
if (command.End.DayNumber - command.Start.DayNumber < apartment.MinimumNights)
{
return (ReserveBookingError)new StayTooShort(apartment.MinimumNights);
}
I left the endpoint alone again.
This time, the build points at the inner switch:
GenericUnions\Endpoints.cs(39,52): warning CS8509: The switch expression does
not handle all possible values of its input type (it is not exhaustive). For
example, the pattern 'Bookings.Unions.StayTooShort' is not covered.
The compiler knows every case type of ReserveBookingError, so it can name the one the switch misses.
Make the Warning an Error
CS8509 is a warning, so the build still passes.
If a one-night booking reaches the endpoint, the switch throws a SwitchExpressionException, which is also a 500.
You can turn the warning into an error in the project file:
<PropertyGroup>
<WarningsAsErrors>CS8509</WarningsAsErrors>
</PropertyGroup>
If your project already has a WarningsAsErrors list, add CS8509 to it.
Now the project doesn't build until the endpoint handles StayTooShort.
Here's the one-night booking with a two-night minimum in each setup:
The check only covers switch expressions without a _ arm.
I also tried a switch statement and an if (result is ...) chain.
Both skipped StayTooShort with 0 warnings.
Summary
A generic union Result<T>(T, Error) replaces the Result class with very few changes.
The handler returns the value or the Error directly, and a generic decorator keeps working.
It doesn't catch a new error code, though, because every failure is still an Error.
Giving each failure a type does.
With the failures in their own union, wrapped in an Outcome<T, TError>, the compiler names the case an endpoint forgot.
That costs a switch inside a switch and a cast for each failure in the handler.
To try it, swap your Result class for the generic union first.
Then move one use case at a time to an Outcome when you want the compiler to check its failures.
The complete sample has every version of the use case, their endpoints, and my build and run output for each step.
Pragmatic Clean Architecture builds the Result class and domain errors into a complete booking application.
Thanks for reading.
And stay awesome!
Frequently Asked Questions
Can C# 15 union types replace the Result pattern?
Yes. The closest replacement is a generic union, union Result<T>(T, Error). The handler returns the value or an Error directly, and the caller matches the result with a switch expression instead of checking IsSuccess. To have the compiler check every failure, give each failure its own record, list them in a union, and wrap it in a generic union such as Outcome<T, TError>.
Does a generic Result<T> union catch a new error?
No. Every failure is an Error, so a switch over Result<T> needs a catch-all Error arm, and the compiler reports CS8509 without it. A new error code falls into that arm with 0 warnings, the same as the _ arm of a switch on Result.Error.Code.
What happens when I add a case to a C# union and a switch does not handle it?
The compiler reports warning CS8509 on the switch expression: it is not exhaustive, and the message names the pattern that is not covered. The build still passes. If the missing case reaches that switch at runtime, it throws a SwitchExpressionException. Add <WarningsAsErrors>CS8509</WarningsAsErrors> to a PropertyGroup in the project file to fail the build instead.
Does the compiler check every place that reads a union?
No. Only a switch expression without a discard arm is checked. In my sample, a switch statement, a chain of if statements with is patterns, and a switch expression with a _ arm all skipped one case of the union, and the build had 0 warnings.
How do I return a C# union from a Minimal API endpoint?
Read it with a switch expression and map each case to a result such as Results.Created, Results.NotFound, or Results.Conflict. If you return the union itself, ASP.NET Core 11 writes the JSON of whichever case it holds with status 200, so a failure case also comes back as 200 OK.
How does a generic validation decorator work with union types?
Make the union generic. With union Result<T>(T, Error), the decorator returns an Error for any Result<T>. With union Outcome<T, TError>(T, TError, ValidationFailed), it returns ValidationFailed for any Outcome. A separate union per use case without a generic wrapper does not work: a decorator over any TResponse cannot return a failure record, and the compiler reports error CS0029.
What are the limits of generic C# 15 unions?
Result<Error> does not compile (error CS0457, ambiguous conversions), because both cases are Error. The compiler also does not chain conversions, so a case of an inner union needs a cast to reach the outer generic union, and a switch over the outer union cannot match a case of the inner one directly (error CS8121).
What is the default value of a C# union?
A union declaration compiles to a struct, and its default value holds no case: the Value property is null. A switch expression that handles every case still throws a SwitchExpressionException for that value, unless it also has a null arm.

