Making a Forgotten Case Break the Build with C# 15 Unions in ASP.NET Core
A small fee calculator example that uses a closed union to describe every possible outcome of an ASP.NET Core endpoint, so that code which forgets to map a result to an HTTP status code fails to compile.
We all know that an endpoint can finish in several different ways: the operation succeeds, the requested record cannot be found, or the incoming data is invalid. We usually express these cases by throwing exceptions or by writing handlers that return an untyped IResult. Then we hope that every branch picks the right HTTP status code. However, the compiler does not know which outcomes exist, so it cannot tell you when you forget one. In this post, I explain how the union declaration introduced in C# 15 can close this gap, using a small fee calculator API as an example. The target audience is developers who write APIs with ASP.NET Core and want to make error handling safer.
The Problem: Outcomes Are Invisible in the Type
In the traditional approach, the return type of a method only describes the successful case. Other outcomes such as not found, invalid input, or authorization failure are either thrown as exceptions or buried inside the handler through calls like NotFound() and BadRequest(). In this case, you have to read the entire code to find out how many different outcomes an endpoint can produce. When you add a new case and forget to map it to an HTTP status code, you get no warning. The bug is usually not noticed until it reaches production.
A Closed Set of Outcomes with C# 15
The default language version that comes with .NET 11 is C# 15, and this version introduces a new type declaration called union. A union is a type that holds the value of exactly one of a fixed set of types. The following example tells the compiler that a payment result can only take one of two forms:
public union PaymentResult(Paid, Declined);
public record Paid(string ReceiptId);
public record Declined(string Reason);
Each case is written as an ordinary record, and when a method returns PaymentResult, it can directly return a value such as new Declined(...). Now the method signature clearly documents which outcomes are possible. In this project, I defined two unions for two endpoints: one for the calculation result and one for the rate card query. Each case has a corresponding HTTP status code.

Image: DEV Community
A notable point in this diagram is that every case has a kind field. The union serializes the selected case as it is and does not carry a separate marker for which case was chosen. On the client side, if you only use the HTTP status code to tell two cases apart, you are forced to rely on that alone. That is why keeping a fixed kind value in every case makes the client's job much easier.
Mapping Outcomes to HTTP Status
The service layer now returns a result instead of throwing exceptions. To convert this result into an HTTP response, I wrote a single mapping method. The switch expression ties each case to a code, and I intentionally left out a default arm. If there were a default arm, newly added cases would silently fall into it, and the compiler would not be able to tell you that a branch was missing.
public static IResult ToHttp(this PaymentResult result) => result switch
{
Paid p => Results.Ok(p),
Declined d => Results.UnprocessableEntity(d),
};
This way, all HTTP status codes are gathered in one file. Handlers only run the business logic and convert the result into a response with ToHttp().
Turning a Missing Case into a Build Error
The real test of this article is to deliberately remove a branch and run the build. When you remove an arm from the switch, the compiler emits the CS8509 warning. By default, this is only a warning, and warnings are easy to ignore. When you add the following line to the project settings, the warning becomes an error and a missing case stops the build:
<WarningsAsErrors>CS8509</WarningsAsErrors>
If a case is missing, the compiler shows one of them as an example. If several cases are missing, it does not list all of them at once and only names one. Even so, the build failing is enough to keep the bug from reaching production.
Validation filter and two "not found" paths
Input validation on the endpoint is done with an endpoint filter. Before the handler runs, the filter checks the request, and if there is an error it creates a ValidationFailed outcome and passes it through the same ToHttp() mapping. This way, validation errors and business results go through a single path. It is worth noting that the filter reads the handler's first parameter with GetArgument<T>(0). If you change the parameter order of the handler, this does not cause a compile error; the problem only appears at runtime.
In this structure, the "not found" case can come from two different places. An undefined layer name is caught in the filter and returns 422. If the layer exists but the request has no rate for the account type, it passes validation and the service returns RateNotFound, which becomes 404. Having two different paths for the same endpoint may be confusing at first, but the responsibility of each one is clear.
What shows up on the OpenAPI side
The application generates the OpenAPI 3.2 document at /openapi/v1.json. The expected response codes for each endpoint are explicitly declared with Produces lines. Without these lines, the generator cannot resolve the IResult returned by the handler and does not see the union's cases. In my experiments, when I returned a union directly from the handler, the generator produced a single schema and only showed the 200 response. That is why each case had to be declared separately. Also, a decimal field can be defined in a different format than expected, which requires reviewing the schema.
What worked and what was a surprise
The union syntax compiled on SDK 11.0.100 without any preview flag. Exhaustive switch expressions over the union really did help catch a missing case at compile time. Gathering the HTTP codes in a single file also made maintenance easier.
The surprise was that a missing case was only a warning by default. In addition, because the union serializes only the selected case, adding a kind field manually became necessary. Relying on the OpenAPI generator to read the union on its own did not work, and explicit Produces declarations were required.
Try it yourself
You need the .NET 11 SDK to run the code. The tests are written at unit, mapping, and endpoint levels, and a total of 15 tests pass. Integration tests call the endpoints and the OpenAPI document through WebApplicationFactory. To run the project, clone the repository and run dotnet test, then start the API with dotnet run and open the OpenAPI address.
Highlights
- C# 15 unions let you define the results of an endpoint as a closed set.
- When a switch expression has no
defaultarm, a missing case is caught at compile time. - Turning the
CS8509warning into an error withWarningsAsErrorsguarantees that a missing case stops the build. - Gathering all HTTP codes in a single mapping method makes maintenance easier.
- The OpenAPI generator does not read unions correctly on its own; each case needs a
Producesdeclaration. - Since the union serializes only the selected case, a
kindfield must be added so that clients can tell the cases apart.
When to use it
The union approach is especially valuable for endpoints with several successful or failed outcomes that depend on business rules. If you want the compiler to enforce an HTTP counterpart for every new case, handling errors with explicit return types instead of exceptions is safer. On the other hand, it still makes sense to use exceptions for truly unexpected errors. Also, if you expect the OpenAPI document to discover every case automatically, you need to plan your Produces declarations from the start.
Comments (0)
No comments yet; be the first.
Leave a comment