Skip to content
HomeAboutContact

C# 15 Union Types vs the Result Pattern (I Built the Same API Both Ways)

By Shady Nagy
Published in .NET
November 24, 2026
9 min read
C# 15 Union Types vs the Result Pattern (I Built the Same API Both Ways)

Table Of Contents

01
Introduction
02
The Problem Both Solve
03
The Result Pattern Today
04
The Same Endpoint with a C# 15 Union
05
What the Compiler Does for You
06
What Union Types Do Not Give You
07
Side by Side
08
Using Both Together
09
When to Use What
10
Key Takeaways
11
Resources
12
Conclusion
13
Feedback and Questions

Introduction

.NET 11 shipped on November 10, 2026, and C# 15 came with it. Its headline feature is union types: a value that is exactly one of a fixed list of types, with a compiler that checks you handled all of them.

Microsoft’s documentation lists “result-or-error returns” as the first scenario for unions. I am one of the two authors named on the Ardalis.Result package, which does result-or-error returns for .NET and has almost 12 million downloads on NuGet. So the question matters to me: does C# 15 make the Result pattern unnecessary?

I did not want to answer from the documentation. I installed the .NET 11 SDK, built the same small API twice, once with Result<T> and once with a union, and ran both. Every code sample and every output in this article comes from that project.

The Problem Both Solve

Ahmed asks your API for order 42. Three things can happen: the order exists, it does not exist, or the id in the request is not valid. None of the three is exceptional, so an exception is the wrong tool for two of them. The method should return what happened, and the caller should deal with each outcome.

Both approaches return the outcome as a value. They differ in who makes sure the caller deals with it.

The Result Pattern Today

With Ardalis.Result 10.1.0 the service returns a Result<Order>:

public record Order(int Id, string Customer, decimal Total);
public static class ResultOrders
{
private static readonly Dictionary<int, Order> Orders = new()
{
[1] = new Order(1, "Ahmed", 250m),
};
public static Result<Order> GetOrder(int id)
{
if (id <= 0)
return Result<Order>.Invalid(new ValidationError("id", "Id must be greater than zero."));
if (!Orders.TryGetValue(id, out var order))
return Result<Order>.NotFound($"Order {id} was not found.");
return order;
}
}

The endpoint is one line, because ToMinimalApiResult() already knows how each status maps to HTTP:

app.MapGet("/result/orders/{id:int}", (int id) =>
ResultOrders.GetOrder(id).ToMinimalApiResult());

This is what the running API returned:

RequestStatusBody
/result/orders/1200{"id":1,"customer":"Ahmed","total":250}
/result/orders/42404Problem details titled “Resource not found.”, with “Order 42 was not found.” in the detail
/result/orders/0400[{"identifier":"id","errorMessage":"Id must be greater than zero.","errorCode":null,"severity":0}]

Result has eleven statuses: Ok, Created, Error, Forbidden, Unauthorized, Invalid, NotFound, NoContent, Conflict, CriticalError and Unavailable. Any method in your application can return any of them, and the mapping to HTTP is written once, inside the package.

The Same Endpoint with a C# 15 Union

A union needs a type for each outcome, then one line that names the set:

public record NotFound(int Id);
public record ValidationFailed(Dictionary<string, string[]> Errors);
public union GetOrderResult(Order, NotFound, ValidationFailed);

The service returns whichever case applies. Each return converts to the union implicitly:

public static class UnionOrders
{
private static readonly Dictionary<int, Order> Orders = new()
{
[1] = new Order(1, "Ahmed", 250m),
};
public static GetOrderResult GetOrder(int id)
{
if (id <= 0)
return new ValidationFailed(new() { ["id"] = ["Id must be greater than zero."] });
if (!Orders.TryGetValue(id, out var order))
return new NotFound(id);
return order;
}
}

The endpoint has to say what each case means for HTTP:

app.MapGet("/union/orders/{id:int}", (int id) =>
UnionOrders.GetOrder(id) switch
{
Order order => Results.Ok(order),
NotFound => Results.NotFound(),
ValidationFailed failed => Results.ValidationProblem(failed.Errors),
});
RequestStatusBody
/union/orders/1200{"id":1,"customer":"Ahmed","total":250}
/union/orders/42404Empty
/union/orders/0400Validation problem details: "errors":{"id":["Id must be greater than zero."]}

The status codes are the same. The bodies differ because here I chose them in the switch, and in the first version the package chose them.

No <LangVersion> setting is needed. C# 15 is the default for projects that target net11.0.

What the Compiler Does for You

Six months later someone adds a fourth outcome:

public record Forbidden(string Reason);
public union GetOrderResult(Order, NotFound, ValidationFailed, Forbidden);

Every switch that does not handle Forbidden now gets this:

warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern 'Forbidden' is not covered.

It is a warning by default. If you ignore it, the switch throws SwitchExpressionException at run time when a Forbidden arrives. I make it a build error in any project that uses unions:

<WarningsAsErrors>CS8509</WarningsAsErrors>

Result cannot do this for you. The following compiles with zero warnings, with nullable reference types enabled:

Result<Order> result = ResultOrders.GetOrder(id);
return result.Value.Customer;

For order 42 the status is NotFound and Value is null, so the request ends in a NullReferenceException and a 500. Nothing told me to check IsSuccess first.

You can switch over result.Status instead, but the status is an enum with eleven values. The compiler then wants all eleven handled (I got “the pattern ‘Ardalis.Result.ResultStatus.Created’ is not covered” for a method that never returns Created), or a discard arm that silences the check for good. A union lists only the outcomes this method can produce, so the check stays useful.

What Union Types Do Not Give You

They Need .NET 11

I compiled the same union for net10.0 with the .NET 11 SDK and <LangVersion>15</LangVersion>:

error CS0518: Predefined type 'System.Runtime.CompilerServices.IUnion' is not defined or imported
error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.UnionAttribute..ctor'

The compiler turns a union into a struct that implements IUnion, and that interface ships with the .NET 11 runtime. .NET 10 is the long-term support release, and it is supported until November 14, 2028, the same day as .NET 11. A team that stays on .NET 10 cannot use unions. Ardalis.Result targets .NET Standard 2.0, .NET 6, 7 and 8, and it ran unchanged in my .NET 11 project.

The Default Value Is Empty

A union is a struct, so it has a default value, and that default holds nothing:

GetOrderResult empty = default; // also what a new array element holds

A switch with an arm for every case type still compiles without a warning, and it throws SwitchExpressionException when it meets this value. Add a null arm wherever a default can reach you:

public static string Describe(GetOrderResult result) => result switch
{
Order o => $"Order {o.Id}",
NotFound n => $"Order {n.Id} was not found",
ValidationFailed v => $"Invalid: {string.Join(", ", v.Errors.Keys)}",
null => "No result at all",
};

No Shared Vocabulary and No HTTP Mapping

Each union is its own type. GetOrderResult and CreateOrderResult have nothing in common, so nothing can map “any result” to a response. You write the mapping per endpoint, or you design shared case types and your own helpers.

That is the work the Result package already did: the statuses, validation errors with an identifier, a message, a code and a severity, PagedResult<T>, and both ToMinimalApiResult() and ToActionResult().

Value Types Are Boxed

The generated struct stores its content as a single object?, so a case like int is boxed. Results that carry classes or records allocate nothing extra. For hot paths with small value types, the documentation describes custom union types that avoid the boxing.

Side by Side

Ardalis.ResultC# 15 union
Works on.NET Standard 2.0 and up.NET 11 only
Outcomes11 shared statusesThe case types you declare, per union
Compiler checks that every outcome is handled❌✅ (warning CS8509)
Reading the value without checkingCompiles, Value is null on failureNeeds a pattern match or a cast
HTTP mappingToMinimalApiResult() or ToActionResult()You write the switch
Validation errors and pagingBuilt inYou design them
Extra types per operationNoneOne union, plus its case types
Package neededYesNo

Using Both Together

You do not have to pick one. In the test project I kept the union inside the application, where I want the compiler to check every caller, and converted it to a Result where HTTP begins:

public static class GetOrderResultExtensions
{
public static Result<Order> ToResult(this GetOrderResult result) => result switch
{
Order order => order,
NotFound missing => Result<Order>.NotFound($"Order {missing.Id} was not found."),
ValidationFailed failed => Result<Order>.Invalid(
failed.Errors.SelectMany(e => e.Value.Select(message => new ValidationError(e.Key, message))).ToList()),
null => Result<Order>.Error("No result was produced."),
};
}
app.MapGet("/both/orders/{id:int}", (int id) =>
UnionOrders.GetOrder(id).ToResult().ToMinimalApiResult());

This endpoint returned exactly what the first one did: 200 with the order, 404 with problem details, 400 with the validation error list. The conversion is itself a checked switch, so a new case type cannot be forgotten there.

There is also a second route. A class can opt in to the union pattern with the [Union] attribute, one public constructor per case type, and a Value property:

using System.Runtime.CompilerServices;
[Union]
public sealed class Outcome
{
public Outcome(Order value) => Value = value;
public Outcome(NotFound value) => Value = value;
public object? Value { get; }
}

A switch over Outcome is checked the same way as one over a declared union. That is how an existing type can take part in exhaustive matching without becoming a union declaration.

When to Use What

SituationMy choice
An application service that ends in an HTTP endpointResult
A project that targets .NET 10 or earlierResult
A library that supports several frameworksResult
A closed set of outcomes that belongs to one operation, on .NET 11Union
State machines, message and command handlingUnion
Domain logic where a missed case is a bug you cannot affordUnion inside, Result at the edge

Key Takeaways

  1. C# 15 union types are released, not a preview feature. On net11.0 they need no language version setting.

  2. A missing case is warning CS8509. Turn it into an error with <WarningsAsErrors>CS8509</WarningsAsErrors>.

  3. Unions need the .NET 11 runtime. They do not compile for .NET 10, the long-term support release.

  4. A default union value holds null. Handle null in the switch wherever a default can reach it.

  5. Result still gives you eleven shared statuses and the HTTP mapping in one call, on every framework.

  6. The two work together: a union where the compiler should check you, a Result where HTTP begins.

Resources

Conclusion

Does C# 15 retire the Result pattern? After building both, my answer is no.

Union types replace the hand-written result classes people built because the language had nothing better, and they do that job well: the compiler now checks that every outcome is handled. A shared set of statuses, the mapping to HTTP, and support for the frameworks most production code still runs on are a different job, and the language did not take that one over.

I expect to use unions for outcomes that belong to one operation, and to keep returning Result<T> from the services that sit behind an API. If you maintain an application on .NET 10, nothing changes for you until you move to .NET 11.

Feedback and Questions

Your insights drive us! For any questions, feedback, or thoughts, feel free to connect:

  1. Email: shady@shadynagy.com
  2. Twitter: @ShadyNagy_
  3. LinkedIn: Shady Nagy
  4. GitHub: ShadyNagy

If you found this guide beneficial, don’t hesitate to share it with your network. Until the next guide, happy coding!


Tags

dotnetcsharpcsharp-15union-typesresult-patternaspnetcore

Share


Previous Article
How I Fixed SSL Certificate Issues on My Website A Complete Guide
Shady Nagy

Shady Nagy

Software Innovation Architect

Topics

Angular
.NET
GatsbyJS
GitHub
Linux
MS SQL
Oracle
AI

Related Posts

Why Your EF Core Tests Are Lying to You (And How SQLite In-Memory Fixes It)

February 1, 2026
8 min

Quick Links

AboutContact Us

Social Media