An API often has more than one successful-looking shape. A link lookup might return a resolved destination, report that no record exists, or reject an invalid identifier. A parser might produce a value, a recoverable warning, or a fatal error.
Before C# 15, those outcomes were commonly represented with object, a broad interface, or a base class. Each option can work, but each leaves the set of possible values more open than the API contract really is. Callers may need defensive casts, and a new outcome can be added without making every caller visibly handle it.
C# 15, released with .NET 11, adds union types for this kind of finite set. A union names its case types, allows those cases to be unrelated, and lets the compiler check that a switch handles the cases you declared. It is a useful addition to the type-system toolbox, not a reason to rewrite every result class.
A result with a closed set of cases
Imagine a lookup operation with three outcomes:
public record class ResolvedLink(Uri Destination);
public record class LinkNotFound(string Code);
public record class InvalidLink(string Reason);
public union LinkLookup(ResolvedLink, LinkNotFound, InvalidLink);
The union declaration says that a LinkLookup contains one of those three case types. The cases do not need a common base class. The compiler-generated union also provides conversions from each case, so a method can return any of them directly:
public static LinkLookup Resolve(string input)
{
if (!Uri.TryCreate(input, UriKind.Absolute, out var uri))
{
return new InvalidLink("The value is not an absolute URI.");
}
if (uri.Host is "example.invalid")
{
return new LinkNotFound(uri.Host);
}
return new ResolvedLink(uri);
}
The caller can use a switch expression without a catch-all arm:
LinkLookup result = Resolve("https://example.com");
string message = result switch
{
ResolvedLink link => $"Destination: {link.Destination}",
LinkNotFound missing => $"No link found for {missing.Code}.",
InvalidLink invalid => $"Invalid link: {invalid.Reason}",
};
This example is illustrative; it was not compiled in this workflow. Its important property is the contract: if LinkLookup gains a fourth case later, existing exhaustive switches become compiler feedback points instead of silently routing the new value through a default branch.
That is different from returning object:
object result = GetSomething();
The object version accepts anything. A caller has to know the undocumented possibilities and decide what to do with an unexpected type. A union makes the intended alternatives visible at the declaration site and at each pattern match.
Exhaustiveness is the practical payoff
Exhaustive matching is most valuable at boundaries where every outcome needs a deliberate policy. An HTTP handler might map a resolved link to a redirect, a missing link to a 404, and invalid input to a 400. A background job might retry one case, record another, and stop on a third.
With an explicit union, adding a new outcome is not just a data-model change. It is a review list generated by the compiler. That can prevent an important case from being hidden behind a broad default arm.
The feature is not the same as making every operation total or infallible. A union does not validate its data, decide whether an error is retryable, or serialize an HTTP response for you. It gives the API a finite vocabulary; the application still has to define the meaning of each case.
Avoid adding a discard merely to silence the compiler when the case is part of the domain contract:
// This hides future cases from the caller.
string message = result switch
{
ResolvedLink link => link.Destination.ToString(),
_ => "Something went wrong",
};
A catch-all can be reasonable at a deliberate compatibility boundary, but it should be a policy decision. Inside business logic, explicit cases usually make changes easier to review.
Remember the default and null cases
The generated union stores its contained value behind a Value property. A default union has a null value, so a helper that normalizes a union must account for that state:
public union OneOrMore<T>(T, IEnumerable<T>)
{
public IEnumerable<T> AsEnumerable() => Value switch
{
T single => [single],
IEnumerable<T> many => many,
null => [],
};
}
The null arm is not decorative. A union variable can be default-initialized, and a case type may itself be nullable. The C# documentation also describes union patterns as matching the contained value rather than treating the wrapper as an ordinary class hierarchy.
This is a good reason to keep union helpers small and to decide what default means for your API. Returning an empty sequence may be right for a convenience type such as OneOrMore<T>, but it would be a dangerous silent fallback for a required lookup result. In that case, make the invalid state observable or prevent it at a higher-level construction boundary.
Union types versus closed hierarchies
Union types and closed hierarchies both support exhaustive pattern matching, but they solve different modeling problems.
Use a union when you want to combine existing, potentially unrelated types:
public record class CachedValue(string Text);
public record class RemoteValue(byte[] Bytes);
public union DataValue(CachedValue, RemoteValue);
The cases do not have to inherit from a shared domain base. This is useful for a result that combines success and failure records, or for an adapter that accepts several representations without pretending they are one inheritance family.
Use a closed hierarchy when the cases are naturally part of one family that your assembly owns:
public closed record class DeliveryState;
public record class Queued(DateTimeOffset At) : DeliveryState;
public record class Sent(Uri Receipt) : DeliveryState;
public record class Failed(string Error) : DeliveryState;
A closed class is implicitly abstract, and direct derivation is restricted to the declaring assembly. The compiler can therefore reason about its direct descendants. Closure is not transitive, though: if a descendant is not also marked closed, it can be extended elsewhere. Mark intermediate levels closed when you need exhaustiveness to continue down the hierarchy.
The choice is about ownership and shape, not about which syntax looks newer. A union is a compact finite sum of case types. A closed hierarchy is an inheritance model with a controlled set of direct descendants.
Availability and project settings
C# 15 is the default language version for projects targeting net11.0 with the .NET 11 SDK. The released union and closed-hierarchy features do not require opting into the preview language version. C# 15's separate memory-safety work remains a preview feature, so do not describe all C# 15 features as equally production-ready.
Let the target framework select the normal language version when possible. The C# language-version guidance warns against setting:
<LangVersion>latest</LangVersion>
latest means the newest version understood by whichever compiler happens to be installed. That can make two build machines accept different syntax, and a newer language feature may depend on runtime or library support that the target framework does not provide.
If a project needs an explicit version, use a specific value and verify it in CI. The compiler can report its selected version with:
#error version
That intentionally produces diagnostic CS8304, which includes the compiler and language versions. Remove the directive after checking the project. As with any target-framework upgrade, build the application and test its dependencies before treating the migration as complete.
Trade-offs worth reviewing
Adding a case is intentionally disruptive. Existing exhaustive switches may need updates. That is usually helpful for domain code, but it can be inconvenient for a public library whose consumers compile against the union. Treat a new case as an API change and document its compatibility implications.
Value types can be boxed. The official C# engineering post describes the ordinary generated representation as storing one object?. If union cases include hot-path value types, measure allocations rather than assuming the syntax is free. Libraries with specialized needs can implement the documented custom union pattern, including non-boxing access methods, but that adds design and maintenance work.
Serialization is still your responsibility. A union describes the in-memory set of cases; it does not automatically define a stable JSON shape, wire discriminator, or versioning policy. Choose and test the representation at an API boundary.
A union is not a substitute for validation. InvalidLink can make invalid input explicit, but the constructor and resolver still need to enforce the invariants that matter. Keep security checks, normalization, and authorization separate from the type declaration.
A compact adoption checklist
Consider a C# 15 union when:
- an operation has a small, deliberately finite set of outcomes;
- the cases may be unrelated types;
- callers should handle every outcome explicitly; and
- adding an outcome should trigger compiler-guided review.
Prefer a closed hierarchy when:
- the values form one conceptual inheritance family;
- your assembly owns the direct descendants; and
- shared members or polymorphic behavior are central to the design.
Before adopting either feature, check the target framework and SDK in CI, decide how null/default values behave, review serialization, and measure value-type-heavy paths if performance matters. These features are most useful when they make a real domain contract clearer—not when they merely replace a short enum or a simple nullable value.