C# union types, and how Result<T> became one
Union types are one of the longest-standing requests in C#'s history. F# has had them from the
start; C# developers have spent years imitating them with base classes, visitor patterns and
Match methods. With C# 15 and .NET 11 they are finally part of the language — and
from version 2.5, QuickResult's Result<T> is one.
What a union type is
A union type holds a single value that is one of a fixed set of types. The types don't need a common base class; the union is what groups them. Because the set is closed, the compiler knows every possible case and can check that you handled all of them.
C# 15 adds a one-line declaration for it:
// A Reading is a double, a bool, or a string. Nothing else.
public union Reading(double, bool, string);
You read a union by switching on its contents. Each arm names one of the case types, and the switch is exhaustive: remove an arm and the compiler tells you which case is no longer covered.
string Render(Reading reading) => reading switch
{
double measure => $"{measure:F1}",
bool isOn => isOn ? "on" : "off",
string text => text
};
That last point is the one that matters. When a case is added to the union later, every switch
that reads it is flagged until it handles the new case. With a class hierarchy and a
default arm, the same change compiles silently and fails at run time.
A Result is the textbook union
"This operation produced a value, or it produced an error" is exactly a union of two cases. It's
the example Microsoft's own union tutorial uses. Until now a C# result type had to simulate the
union: store both a value and an error, expose an IsSuccess flag, and trust callers
to check the flag before reading the right property — or offer a Match method that
takes one lambda per case.
Match does force both cases to be handled, which is why QuickResult has always had
it. But it is a library convention, not a language feature. You can't add an arm for a specific
error type, you can't use it in an is expression, and the compiler's pattern
matching knows nothing about it.
Result<T> is a union of T and IError
On .NET 10 and later, Result<T> is a C# union whose two cases are the success
value T and the failure IError. You can switch on a result directly:
Result<int> result = ParsePositive(input);
string text = result switch
{
int value => $"Got {value}",
IError error => $"Failed: {error.Message}"
};
if (result is IError failure)
Console.WriteLine(failure.Message);
Because the failure case is an interface, your own error types get their own arms. The compiler
still requires the general IError arm, so an error type you didn't anticipate
can't slip through:
string status = result switch
{
int value => "200",
NotFoundError => "404",
IError => "500"
};
This example runs the real package in your browser. Try 3, then 25, then something that isn't a number:
Switch on a Result as a C# union
On .NET 10 and later, Result<T> is a C# union of T and IError. With C# 15 you can switch on the result itself by type — the compiler checks that both cases are handled — and a value or an error converts implicitly to a result, so a method can return either directly.
public sealed record OutOfStockError(string Message) : IError;
Result<int> Reserve(string text)
{
if (!int.TryParse(text, out var requested) || requested <= 0)
return new Error("Quantity must be a positive whole number");
if (requested > 10)
return new OutOfStockError($"Only 10 in stock, {requested} requested");
return requested;
}
var result = Reserve(quantity);
var line = result switch
{
int reserved => $"Reserved {reserved} widgets",
OutOfStockError e => $"409 Conflict: {e.Message}",
IError e => $"400 Bad Request: {e.Message}",
};
Console.WriteLine(result);
Console.WriteLine(line);
Return a value or an error directly
Each case type of a union converts to the union implicitly. For a result that means a method can
simply return the value or the error, with no Result.Success(...) or
Result.Failure(...) wrapper:
Result<int> ParsePositive(string text)
{
if (int.TryParse(text, out var number) && number > 0)
return number; // becomes Success(number)
return new Error("Not a positive integer"); // becomes Failure(...)
}
The factory methods are still there and still the clearest choice when the types alone would be ambiguous — see the edge cases below.
How QuickResult implements it
The one-line union declaration is shorthand: it generates a new struct that stores
its contents in a single object? field. That is ideal for a new type, but it didn't
fit an existing one. Result<T> is a class with an established API —
Map, Bind, Match, LINQ query support. A declared union
would have been a different type, a struct that couldn't keep the class's fields, and it
would have boxed every int stored in a Result<int>.
C# 15 has a second route for exactly this situation: a custom union type. Any class or
struct marked with [Union] that exposes a small set of members gets the same
language support as a declared union. QuickResult uses it in three steps.
1. Mark the existing class as a union
Result<T> gains the [Union] attribute and keeps every existing
member, so calls to Map, Bind, Match and the rest are
source-compatible. The one thing that changes for C# 15 callers is how type patterns read a
result, which is covered in the edge cases below.
2. Describe the cases through a member provider
The compiler needs to know the case types and how to read them. Rather than add those members
to Result<T>'s public surface, QuickResult declares them on a nested interface
named IUnionMembers, which the language recognises as a union member
provider, and implements that interface explicitly:
[Union]
public sealed partial class Result<T> : Result<T>.IUnionMembers
{
object? IUnionMembers.Value => IsSuccess ? _value : _error;
bool IUnionMembers.HasValue { get { ... } } // false for a null success
bool IUnionMembers.TryGetValue(out T value) { ... } // read as a T, no boxing
bool IUnionMembers.TryGetValue(out IError error) { ... } // read as an IError
static Result<T> IUnionMembers.Create(T value) => Success(value);
static Result<T> IUnionMembers.Create(IError error) => Failure(error);
// The compiler finds the union's members here, not on Result<T> itself.
public interface IUnionMembers
{
object? Value { get; }
bool HasValue { get; }
bool TryGetValue(out T value);
bool TryGetValue(out IError error);
static abstract Result<T> Create(T value);
static abstract Result<T> Create(IError error);
}
}
The two Create methods tell the compiler what the cases are (T and
IError) and give it the implicit conversions. The two TryGetValue
overloads are how a switch arm reads the contents with its own type, so matching a
Result<int> never boxes the integer. IUnionMembers is public
because the language requires it, but it is compiler infrastructure, not something to call.
3. Work on .NET 10 as well as .NET 11
UnionAttribute ships in .NET 11, but the compiler recognises it by name. The .NET 10
build of QuickResult declares its own internal copy, so a project that targets .NET 10 gets
union behaviour as long as it is compiled with the C# 15 compiler.
What you need to use it
| Your project targets | What to do |
|---|---|
| .NET 11 | Nothing. C# 15 is the default language version. |
| .NET 10 | Build with the .NET 11 SDK and set <LangVersion>15</LangVersion> (or latest). |
| .NET Framework, .NET 8, .NET 9 | These use the .NET Standard 2.0 build, which is not a union. Everything else — Match, Map, Bind, LINQ — works the same. |
dotnet add package QuickResult
Edge cases worth knowing
- Null success values. A successful result holding
nullmatches neither arm, so add anullarm whenTis nullable. For the same reasonresult is nullis true for such a result; useIsSuccessto tell a null success from anything else. - When T overlaps IError. If
TisIError,objector an error type, a type pattern can't tell success from failure: anIErrorarm also matches a successful value that happens to be an error, and aTarm also matches a failure whose error is aT. UseIsSuccessorMatchfor those results. Implicit conversion follows the same overlap: an error assigned to aResult<object>becomes a failure, and assigning one to aResult<IError>does not compile, so create those with the explicitSuccess(...)andFailure(...)factories. - Patterns now look inside the result. Under C# 15,
result is Result<int>no longer compiles whenresultis already aResult<int>, because the pattern tests the contents. Matching fromobject(obj is Result<int> r) and property patterns such asresult is { IsSuccess: true }are unaffected.
Match, switch, or LINQ?
Nothing was taken away, so use whichever reads best:
switchwhen you are consuming a result at the edge of your code and want arms for specific error types.Matchwhen you want one expression that also works on older target frameworks, or an async version (MatchAsync).- LINQ query syntax when you are composing several steps and want the first failure to short-circuit the rest — including steps that mix sync and async.