C# 15 (2026): union types and closed hierarchies
What you’ll learn
Section titled “What you’ll learn”- What C# 15 added, which SDK and Visual Studio version it needs, and how it is enabled.
- How union types and
closedhierarchies give exhaustiveswitchexpressions without a discard arm, and wherenullstill sneaks in. - How
with(...)passes capacity and comparers to collection expressions, and why it doesn’t steer overload resolution. - How labeled
breakandcontinuereplace flags andgoto. - The source breaks to check when upgrading from C# 14, including a compiler change that affects every language version.
Summary
Section titled “Summary”C# 15 is the .NET 11 edition of the language and the current release.
Release at a glance
Section titled “Release at a glance”| Item | Value |
|---|---|
| Released | November 2026 |
| Paired runtime | .NET 11 (STS) |
| Minimum toolset | .NET 11 SDK (11.0.100); “a compatible version of Visual Studio 2026” (no minimum update stated by Microsoft) |
| Default for TFM | net11.0 |
LangVersion |
15.0 (or 15) |
| Support today | Supported: .NET 11 is supported until November 2028. Microsoft states that C# 15 “is supported only on .NET 11 and newer versions” |
| Previews in this release | Memory safety, with LangVersion preview (see the C# 16 preview page) |
Unions also need UnionAttribute and IUnion from System.Runtime.CompilerServices, which the .NET 11 runtime includes.
Feature map
Section titled “Feature map”| Feature | Weight | Mainly for | Deep dive |
|---|---|---|---|
| Union types | Headline | App and library code | Union types |
| Closed hierarchies | Headline | App and library code | Closed hierarchies |
| Collection expression arguments | Headline | App code, performance | Collection expression arguments |
Labeled break and continue |
Headline | App code | Labeled break and continue |
| Extension indexers | Smaller | Library code | Extension indexers |
| Non-virtual static interface members on older runtimes | Smaller | Multi-targeted libraries | This page |
| Memory safety | Preview | Interop and parsing code | C# 16 preview |
How to run the samples
Section titled “How to run the samples”Install the .NET 11 SDK, create a console app with dotnet new console (it targets net11.0 and therefore C# 15), and replace Program.cs with the sample. The samples use the template’s implicit using directives and <Nullable>enable</Nullable>, and set the invariant culture where they print numbers or dates. They were compiled with the compiler from the .NET 11.0.100 SDK (compiler 5.12.0) using -langversion:15.0 against the net11.0 reference assemblies, and run on .NET 11.0.0. Output is shown under each sample. Compiled with LangVersion 14.0 instead, the union sample fails with the misleading “CS8803: Top-level statements must precede namespace and type declarations”, because union isn’t a keyword there yet.
Headline feature: union types
Section titled “Headline feature: union types”Problem
Section titled “Problem”A payment call in OrdersPortal returns an approval, a decline or a pending state. Before C# 15 you modeled that with a marker interface or an abstract base class, and every switch needed a discard arm because the compiler couldn’t know the set was complete. Adding a fourth outcome compiled cleanly and failed at run time.
How it works
Section titled “How it works”union Name(A, B, C) declares a value that is exactly one of the listed case types. Each case type converts implicitly to the union. Type patterns on a union test its contents, and a switch that handles every case type is exhaustive. The compiler lowers a union declaration to a struct marked [Union] that implements IUnion, with one constructor per case type and a Value property of type object?.
Example
Section titled “Example”using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
PaymentResult ok = new Approved("AUTH-77", 49.90m);PaymentResult no = new Declined("insufficient_funds");PaymentResult unset = default; // a default union holds null
foreach (var result in new[] { ok, no, unset }){ Console.WriteLine(Describe(result));}
static string Describe(PaymentResult result) => result switch{ Approved a => $"approved {a.Amount:F2} ({a.AuthCode})", Declined d => $"declined: {d.Reason}", Pending => "pending", null => "no result", // keep this arm: default(PaymentResult) reaches here};
public record class Approved(string AuthCode, decimal Amount);public record class Declined(string Reason);public record class Pending;
public union PaymentResult(Approved, Declined, Pending);Output:
approved 49.90 (AUTH-77)declined: insufficient_fundsno resultRemove the Pending arm and the compiler reports “warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern ‘Pending’ is not covered.” That warning is the point of the feature: adding a case type flags every incomplete switch.
Gotchas
Section titled “Gotchas”- Default values contain null.
default(PaymentResult), an uninitialized field or an array element holds a union whoseValueis null. When all case types are non-nullable, the compiler may not warn about a missingnullarm, and the switch throwsSwitchExpressionExceptionat run time. Prefer an explicitnullarm to_, because a discard also hides newly added cases. - Untyped patterns read the union, not its contents.
result is { }always matches a struct union, even whenValueis null; useresult is not null.result is PaymentResultis a compile-time error (CS8121). - Boxing. The generated form stores everything as
object?, so value-type cases are boxed. For hot paths with value-type cases, write a custom union type with the non-boxingHasValue/TryGetValuepattern. - No equality or deconstruction of its own. A union answers “which case is it?”; use records for the case types when you need value equality.
When not to use it
Section titled “When not to use it”Don’t use a union when the alternatives share behavior you want to call polymorphically; an interface or base class with virtual members is clearer. A union can’t carry its own data either: if every case needs a shared field such as a timestamp, a closed hierarchy with a base record fits better.
Headline feature: closed hierarchies
Section titled “Headline feature: closed hierarchies”Problem
Section titled “Problem”Unions compose existing, unrelated types. Often the alternatives are your own types that share data or behavior and naturally form a class hierarchy, and you still want exhaustive switch expressions.
How it works
Section titled “How it works”The closed modifier on a class means it can only be derived from inside its declaring assembly, so the compiler knows every direct descendant. A closed class is implicitly abstract and can’t also be sealed, static or explicitly abstract.
Example
Section titled “Example”using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
ShipmentState[] states = [new Packed(), new InTransit("ParcelCo"), new Delivered(new DateOnly(2026, 11, 12))];foreach (var state in states){ Console.WriteLine(Describe(state));}
// No default arm: the compiler knows every direct descendant of ShipmentState.static string Describe(ShipmentState state) => state switch{ Packed => "packed, waiting for pickup", InTransit(var carrier) => $"in transit with {carrier}", Delivered(var on) => $"delivered on {on:yyyy-MM-dd}",};
public closed record class ShipmentState;public record class Packed : ShipmentState;public record class InTransit(string Carrier) : ShipmentState;public record class Delivered(DateOnly On) : ShipmentState;Output:
packed, waiting for pickupin transit with ParcelCodelivered on 2026-11-12Gotchas
Section titled “Gotchas”- Closure isn’t transitive. A non-closed descendant of a closed class can be derived from in other assemblies. Mark intermediate classes
closedtoo if you need exhaustiveness further down. closed sealedis an error: “CS9381: ‘X’: a closed type cannot be sealed or static”.- Closing is a breaking change for anyone outside the assembly who already derives from the class.
When not to use it
Section titled “When not to use it”Don’t close a hierarchy that plugin authors or other teams are meant to extend, and don’t close a class just to silence a discard arm when the set of cases really is open.
Headline feature: collection expression arguments
Section titled “Headline feature: collection expression arguments”Problem
Section titled “Problem”C# 12 collection expressions couldn’t pass constructor arguments, so a list with a known capacity or a set with a comparer went back to new HashSet<string>(comparer) { ... }.
How it works
Section titled “How it works”A with(...) element placed first in the brackets passes its arguments to the target’s constructor, or to a [CollectionBuilder] create method before the ReadOnlySpan<T> parameter. Arguments are evaluated before the elements, left to right. Interface targets accept limited arguments: IList<T> and ICollection<T> take a capacity (the compiler creates a List<T>), while IEnumerable<T>, IReadOnlyCollection<T> and IReadOnlyList<T> accept only an empty with(). Arrays and spans don’t support with(...).
Example
Section titled “Example”string[] skus = ["SKU-1", "SKU-2", "SKU-3"];
// A picklist that will grow: reserve capacity up front.List<string> picklist = [with(capacity: skus.Length * 2), .. skus];Console.WriteLine($"{picklist.Count}/{picklist.Capacity}");
// Handling tags typed by warehouse staff: compare without case.HashSet<string> tags = [with(StringComparer.OrdinalIgnoreCase), "Fragile", "FRAGILE", "fragile", "Cold"];Console.WriteLine(tags.Count);
// Interface targets: IList<T> accepts a capacity and creates a List<T>.IList<int> quantities = [with(capacity: 100), 1, 2, 3];Console.WriteLine(quantities is List<int>);
// A comparer for a sorted lookup of bin codes.SortedSet<string> bins = [with(StringComparer.Ordinal), "b-2", "A-1", "a-1"];Console.WriteLine(string.Join(",", bins));Output:
3/62TrueA-1,a-1,b-2Gotchas
Section titled “Gotchas”- Arguments don’t choose overloads. With
Print(List<string>)andPrint(HashSet<string>)overloads,Print([with(StringComparer.OrdinalIgnoreCase), "one"])is ambiguous (CS0121): the compiler ignores thewith(...)arguments when it picks the target type. Assign to a typed variable first. - No type inference from arguments.
Use([with(10)])forUse<T>(List<T>)fails with CS0411; writeUse<int>(...). withused to be a method name.[with(x, y), z]called a method namedwithin C# 14; in C# 15 it is constructor arguments. Write@with(...)to call the method.
When not to use it
Section titled “When not to use it”Skip with(capacity: ...) for small, fixed collections, where it only adds noise, and keep an explicit new when the constructor call is the important part of the line, for example a custom comparer with several settings.
Headline feature: labeled break and continue
Section titled “Headline feature: labeled break and continue”Problem
Section titled “Problem”Leaving two nested loops at once needed a Boolean flag checked at every level, or a goto to a label after the loops. Both obscure the intent.
How it works
Section titled “How it works”Put a label on a loop or switch statement. break label; exits that statement, and continue label; starts the next iteration of that loop. The label must be directly on the statement it names. Unlabeled break and continue keep their original behavior, and the IDE0410 style rule flags the flag and goto patterns that a labeled jump can replace.
Example
Section titled “Example”// Warehouse bins: 0 = empty, otherwise a SKU number.int[,] bins = { { 0, 0, 9 }, { 0, 7, 0 }, { 5, 0, 9 } };
(int Row, int Col)? found = null;search: for (int r = 0; r < 3; r++){ for (int c = 0; c < 3; c++) { if (bins[r, c] == 7) { found = (r, c); break search; // leaves both loops } }}Console.WriteLine(found);
int rowsWithSku9 = 0;rows: for (int r = 0; r < 3; r++){ for (int c = 0; c < 3; c++) { if (bins[r, c] == 9) { rowsWithSku9++; continue rows; // count each row once, then move on } }}Console.WriteLine(rowsWithSku9);Output:
(1, 1)2Gotchas
Section titled “Gotchas”- The label names an enclosing loop or
switch, not a position:break other;whereotherlabels an unrelated statement fails with CS9393 (“No enclosing loop or switch statement with the label ‘other’ out of which to break”), which is what makes it safer thangoto. continue label;with a label on aswitchstatement fails with CS9394, becausecontinueapplies only to loops.
When not to use it
Section titled “When not to use it”If the nested loops search for one item, extracting a method and using return is often clearer still. Deeply nested loops with several labeled jumps are a sign the code wants splitting, not more labels.
Smaller changes
Section titled “Smaller changes”using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
// Extension indexer: daily order counts arrive as a sequence from a report API.IEnumerable<int> dailyOrders = Enumerable.Range(100, 7);Console.WriteLine(dailyOrders[2]); // extension indexer on IEnumerable<int>
// Non-virtual static interface member: a unit helper that lives on the interface.Console.WriteLine(IMeasurement.ToMeters(250));
public static class SequenceIndexer{ extension(IEnumerable<int> sequence) { public int this[int index] => sequence.ElementAt(index); }}
public interface IMeasurement{ public static double ToMeters(double centimeters) => centimeters / 100;}Output:
1022.5- Extension indexers. C# 14
extensionblocks can now declare indexers; because indexers are instance members, the block must name its receiver. Be careful with what an indexer implies:dailyOrders[2]looks O(1), butElementAton a lazy sequence enumerates from the start on every access. Reserve extension indexers for receivers with cheap random access. - Non-virtual static interface members on older runtimes. The scenario is a library that multi-targets, say,
netstandard2.0(which .NET Framework consumes) andnet11.0. Before C# 15, a static helper such asIMeasurement.ToMetersin the interface failed to compile for thenetstandard2.0build, because that target’s runtime doesn’t support default interface implementations. Now the helper compiles for every target. Instance default implementations,static abstractandstatic virtualmembers, and protected interface members still need runtime support. The sample runs on .NET 11, so it shows the syntax rather than the older runtime. - Memory safety (preview). The first step of a multi-release redesign of
unsafe, available only withLangVersionpreviewand, for the caller rules, theupdated-memory-safety-rulesfeature flag. Microsoft documents it as a C# 15 preview; its breaking changes are labeled C# 16. See the C# 16 preview page. - Library support. System.Text.Json in .NET 11 adds C# and F# union support.
Breaking changes
Section titled “Breaking changes”From Microsoft’s compiler breaking-change list for .NET 10.0.100 through .NET 11.0.100 (Visual Studio 2026 version noted where Microsoft gives one):
unionandclosedare contextual keywords in type declarations (18.10). A field declared asunion OldField;is now parsed as a union declaration (CS9370), andclosed oldField;as an incomplete declaration (CS1519). Escape with@unionor@closed.with(...)as the first collection element is constructor arguments, not a call to a method namedwith(18.4). Use@with(...).- Parsing of
withwithin a switch-expression arm (18.4). A pattern such as(X.Y) when a > b =>used to be read as a cast of an identifier namedwhen; it is now a constant pattern followed by awhenclause. In testing,x switch { (Y.A) when a > b => "gt", _ => "other" }failed to parse with the .NET 10 SDK compiler (CS1003) and compiled with the .NET 11 compiler. nameof(this.Member)inside attributes is now an error, matching the specification. Removethis..- Dynamic
&&/||with an interface-typed left operand now fails at compile time (CS7083) instead of throwing at run time. - Synthesized
ref readonlydelegates and local functions needSystem.Runtime.InteropServices.InAttribute(CS0518 otherwise).
Span-typed collection expressions have the declaration-block safe-context (18.3). The C# 12 collection expressions specification says a collection expression whose target is Span<T> or ReadOnlySpan<T> can only be referenced inside the block that declares it, because the compiler may stack-allocate its storage there. Earlier compilers used the wider function-member context, so a span created inside a loop could be assigned to a scoped span declared outside it. That assignment now fails. This is a compiler change, not a language-version change: in testing, the fragment below compiled with the .NET 10 SDK compiler at LangVersion 12 and failed with “CS8352: Cannot use variable ‘items’ in this context because it may expose referenced variables outside of their declaration scope” with the .NET 11 compiler at both LangVersion 12 and 15.
// Fragment: rejected by the .NET 11 compiler at any LangVersion.scoped Span<int> items1 = default;foreach (var x in new[] { 1, 2 }){ Span<int> items = [x]; if (x == 1) items1 = items; // CS8352: 'items' may only live inside the loop body}Use an array (int[] items = [x];, which converts to Span<int>) or declare the span outside the loop and overwrite its elements.
Upgrade steps and gotchas
Section titled “Upgrade steps and gotchas”- Retarget to
net11.0to get C# 15 by default. RaisingLangVersionto 15 on anet10.0project is unsupported, and unions need runtime types that only .NET 11 provides. - Decide between .NET 10 and .NET 11. .NET 10 is LTS and .NET 11 is STS, with the same end date (see the support row above). Teams that upgrade every year can take .NET 11 now; teams that upgrade every few years may stay on .NET 10 and C# 14 and skip to .NET 12.
- Update the SDK first, even if you stay on
net10.0. The span safe-context andwithparsing changes come with the .NET 11 compiler, not with C# 15, so a new SDK can break a build that doesn’t change its target. - Search for identifiers named
union,closedandwithbefore upgrading, and fix them with@. - Introduce unions and closed hierarchies at boundaries where exhaustiveness pays off, such as result types and state machines, and treat CS8509 as an error.
Where it sits in the language’s evolution
Section titled “Where it sits in the language’s evolution”Pattern matching began in C# 7 and grew through switch expressions (C# 8), relational and logical patterns (C# 9) and list patterns (C# 11). Until C# 15 it lacked a way to say “these are all the cases”, so exhaustiveness for class hierarchies needed a discard. Unions and closed hierarchies fill that gap. Collection expression arguments finish the collection expression story from C# 12, and extension indexers extend the C# 14 extension blocks.
Interview questions
Section titled “Interview questions”How is a C# 15 union represented at run time?
As a struct marked [Union] that implements IUnion, with a constructor per case type and an object? Value property. A type you write yourself becomes a union type too if it carries [Union] and follows the same pattern, which is how you can control storage.
When do you choose a union over a closed hierarchy?
A union composes existing, possibly unrelated types, including types you don’t own, like int and string. A closed hierarchy fits when the alternatives are your own types that share a base, data or behavior. Both give exhaustive switch expressions.
A web API returns PaymentResult as JSON. What does System.Text.Json write, and what goes wrong when a client reads it back?
In .NET 11 the serializer writes the active case directly, with no wrapper and no $type discriminator: an Approved becomes {"AuthCode":"AUTH-77","Amount":49.90}, and a default union becomes null. Deserialization picks the case from the JSON token kind, and Approved and Declined are both objects, so in testing reading that JSON back threw JsonException. Either add [JsonUnion(TypeClassifier = typeof(JsonUnionTypeStructuralClassifier))], which chooses by property names and can change behavior as the records evolve, or model the result as a closed hierarchy with [JsonPolymorphic(InferClosedTypePolymorphism = true)], which writes a discriminator.
Your codebase already uses a library “one of” type, such as a generic OneOf<T1, T2> struct with a Match method. Should you replace it with a C# 15 union?
For new code, a language union gives what the library type couldn’t: implicit conversions from each case, and switch exhaustiveness with CS8509 instead of lambdas passed to Match. A library type that stores each case in a typed field keeps one advantage: it avoids boxing value-type cases, which the generated union can’t. You don’t have to choose all at once: a custom type that carries [Union], follows the union pattern and implements HasValue/TryGetValue gets the language behavior without boxing, so an adapter can bridge the two while call sites move from Match lambdas to switch expressions.
Senior scenario: your API returns Task<OrderResult> where OrderResult is an abstract class with five subclasses, and bugs come from unhandled cases. How do you migrate, and what do you watch out for?
Make OrderResult closed if the subclasses live in the same assembly; that keeps the public type and gives exhaustiveness immediately. Treat CS8509 as an error and remove discard arms. Use a union only if the cases are unrelated types. Check consumers in other assemblies: they can’t derive new subclasses after closing, which is a breaking change to document. Closing alone doesn’t add a JSON discriminator, so check how the hierarchy is serialized before relying on it across a service boundary.
Key takeaways
Section titled “Key takeaways”- C# 15 is the .NET 11 language version and the default for
net11.0. - Unions compose existing types; closed hierarchies close your own class trees. Both make
switchexpressions exhaustive. - Default unions contain null, so keep an explicit
nullarm. with(...)passes constructor arguments to collection expressions but doesn’t influence overload resolution.- The .NET 11 compiler tightens span collection-expression lifetimes at every
LangVersion; update the SDK deliberately.
Related pages
Section titled “Related pages”- C# versions: release history and guides
- Union types
- Closed hierarchies
- Collection expression arguments
- Extension indexers
- Labeled break and continue
- C# 14 (2025) and C# 16 preview
Official release notes
Section titled “Official release notes”- What’s new in C# 15
- The history of C#: C# version 15
- Union types (C# reference)
- Feature specification: unions
- Feature specification: closed hierarchies
- Collection expression arguments (language reference)
- Jump statements: labeled break and continue
- Static interface members and runtime support
- Compiler breaking changes from .NET 10.0.100 to .NET 11.0.100
- C# language versioning
- Releases and support for .NET