.NET 11 is generally available and ships with C# 15, the default language version for projects that target net11.0 in the .NET 11 SDK. This is not a release of small tweaks: it brings union types, closed hierarchies, extension indexers, labeled break and continue, and a first step toward a new definition of memory safety. At the same time the runtime introduces native async, and the SDK lets single-file programs grow across several files. This guide walks through the new paradigms one by one, using only what the official documentation states. If you are coming from C# 14, start with the guide to C# 14 and .NET 10.
What changes in the way you write C#
The common thread is that the compiler and the runtime take over things that used to be conventions or hand-written support code. An exclusive choice between different types becomes a language construct (union), with exhaustiveness checked by the compiler. A class hierarchy can declare itself closed. The async/await machinery, until now built on compiler-generated state machines, can be managed by the runtime itself. And a C# program can live in a single file without being confined to that one file.
For a more narrative tour of the language changes there is also the article What's new in C# 15; here the goal is to look at the changes as paradigms, that is, as different ways to model data, run asynchronous code and organize a program.
Union types: exclusive choices in your data model
What it is
C# 15 introduces union types, which represent a value that can be one of several case types. You declare them with the union keyword. Unions provide implicit conversions from each case type, and the compiler ensures that switch expressions are exhaustive across all cases.
public record class Cat(string Name);
public record class Dog(string Name);
public record class Bird(string Name);
public union Pet(Cat, Dog, Bird);
Pet pet = new Dog("Rex");
string name = pet switch
{
Dog d => d.Name,
Cat c => c.Name,
Bird b => b.Name,
};
Why it matters
When a value can be "a cat, a dog or a bird" and nothing else, the data model says so explicitly. If a case is added to the union later, any switch that does not handle it is flagged by the compiler instead of failing at run time. This is the kind of guarantee that used to require conventions or carefully designed hierarchies.
Unions and System.Text.Json
The .NET 11 libraries already know how to serialize unions. A union such as Reading(int, string) is written directly as its active case, with no wrapper and no $type discriminator: the string case "hello" produces "hello", the int case 42 produces 42, and a struct union with no active case produces null.
public union Reading(int, string);
Reading reading = new("hello");
string json = JsonSerializer.Serialize(reading);
Reading copy = JsonSerializer.Deserialize<Reading>(json);
Console.WriteLine(json); // "hello"
Console.WriteLine(copy.Value); // hello
On deserialization the case is chosen from the JSON token kind: number, string, Boolean, array or object. Two object cases share a token kind, so the default classifier cannot tell them apart. For that reason the documentation points to JsonUnionAttribute with the built-in JsonUnionTypeStructuralClassifier, which picks the case from root-level property names and required properties.
[JsonUnion(TypeClassifier = typeof(JsonUnionTypeStructuralClassifier))]
public union PetUnion(Dog, Cat);
public sealed record Dog(string Name, string Breed);
public sealed record Cat(string Name, int Lives);
With the payload {"Name":"Misty","Lives":9}, the Lives property selects Cat. The classifier does not inspect property values or nested content; if the payload matches zero or several cases, deserialization throws JsonException. It does not support multiple non-object cases with the same token kind, nested unions, polymorphic cases or ReferenceHandler.Preserve. For other rules you derive from JsonTypeClassifierFactory and register it on the union, on a JsonSerializerOptions instance or on a source-generated context. JsonNumberHandlingAttribute is honored on unions, and the source generator no longer reports SYSLIB1227 for unions that use custom converters.
The runtime side and F#
.NET 11 also introduces System.Runtime.CompilerServices.UnionAttribute and IUnion, the runtime side of the C# discriminated-union design. The source states that they are not directly user-facing yet: the expected producers are the C# compiler and source generators, but they ship in the framework so libraries can author against that surface now.
For F#, the System.Text.Json documentation also describes serialization of discriminated unions: cases without fields become JSON strings, and cases with fields become objects carrying a $type discriminator. For example, given this definition, Point becomes "Point" and Circle 3.14 becomes {"$type":"Circle","radius":3.14}.
type Shape =
| Point
| Circle of radius: float
| Rectangle of height: float * length: float
F# support relies on reflection only: it does not work with System.Text.Json source generation, trimming or Native AOT.
How to enable it
C# 15 is the default language version for projects that target net11.0 in the .NET 11 SDK; for unions the source asks for no further settings.
Closed hierarchies: exhaustiveness with classes too
What it is
The closed modifier on a class declares a closed hierarchy: the class can only be derived from within its declaring assembly, so the set of direct descendants is fixed at compile time.
public closed record class GateState;
public record class Closed : GateState;
public record class Open(float Percent) : GateState;
string Describe(GateState state) => state switch
{
Closed => "closed",
Open(var percent) => $"{percent}% open",
// No warning: every direct descendant of 'GateState' is handled.
};
Why it matters
Because the compiler knows every direct descendant, a switch that handles each one is exhaustive and needs no default arm. It is the alternative to unions when you would rather stay in the world of classes and records.
The rules to remember, from the source: closed is a contextual keyword; a closed class is implicitly abstract and cannot be combined with sealed, static or an explicit abstract; derivation is not transitive, so a non-closed descendant of a closed class can still be derived from in other assemblies. To extend exhaustiveness checking down the hierarchy, mark the intermediate descendants closed as well.
Native runtime async: what changes for async/await users
What it is
.NET 11 introduces Runtime Async (called "Runtime Async V2" in the source), a significant step toward replacing compiler-generated async state machines with runtime-managed suspension and resumption. Instead of the compiler emitting state-machine classes, the runtime itself tracks async execution. The source lists cleaner stack traces, better debuggability and lower overhead. For the runtime side in depth, see CLR and Runtime Async in .NET 11.
What it means for your code
The async/await code you write stays the same: what changes is how it runs. The most visible effect is live stack traces, the ones that profilers, debuggers and new StackTrace() see during execution. With compiler-generated async, each async method produces several frames of infrastructure; with Runtime Async the real methods appear directly. In the documentation's example with three nested methods, the trace goes from 13 frames with the infrastructure visible to 5 frames that show the real call chain. Exception stack traces (catch (Exception ex)) already look the same with or without Runtime Async.
Other points stated by the source:
- Runtime Async supports NativeAOT and ReadyToRun, reuses continuation objects more aggressively and avoids saving unchanged locals;
- breakpoints bind correctly inside runtime-async methods, and the debugger steps through
awaitboundaries without landing in generated infrastructure; - the .NET runtime libraries are compiled with
runtime-async=onand no longer contain compiler-generated state machines: this makes it possible to migrate an entire app that has only library dependencies, and the product team welcomes reports on throughput and library size; - covariant
TasktoTask<T>overrides work through a runtime-generated thunk, also in NativeAOT; - the async profiler instruments both runtime-async methods and compiler-generated state machines, with one consistent event model.
Related performance work
The source lists several optimizations: the JIT compiles a dedicated runtime-async version of synchronous task-returning methods, tail-merges suspension points, caches continuations, flows async versions through tiered compilation and recognizes common factories such as Task.FromResult, Task.CompletedTask and ValueTask.FromResult. In addition, async continuations can skip capturing and restoring the ExecutionContext when there is nothing to restore; Task, Task<T>, ValueTask, ValueTask<T> and the runtime-async path benefit, especially apps that use ConfigureAwait(false) and AsyncLocal<T> sparingly.
How to enable it
In a project that targets net11.0, add this property to the project file. EnablePreviewFeatures is no longer required.
<PropertyGroup>
<Features>runtime-async=on</Features>
</PropertyGroup>
The DOTNET_RuntimeAsync and UNSUPPORTED_RuntimeAsync environment variables have been removed. To opt out of Runtime Async per project, set this in the project file:
<UseRuntimeAsync>false</UseRuntimeAsync>
Single-file programs and scripting
What it is
File-based apps let you run a C# program from a single file, for example with dotnet run app.cs. In .NET 11 the paradigm grows: the #:include directive lets you move shared helpers into separate files without giving up the file-based workflow.
#:include helpers.cs
#:include models/customer.cs
Console.WriteLine(Helpers.FormatOutput(new Customer()));
Why it matters
Until now a C# script that grew forced a move to a full project. With #:include you can keep the script as the entry point and split models and utilities into their own files. For the SDK tooling, see also the .NET 11 SDK and CLI tools.
Other file-based app improvements
#:propertydirectives accept quoted values that contain spaces, and the#:package,#:projectand#:refdirectives accept trailingName=Valuetokens that set MSBuild item metadata (for exampleAliases, which lets the app reference the package through anexternalias). Property names can no longer contain:.- The Native AOT command-line path can reuse build outputs when it runs an unchanged file-based app (
dotnet run --file app.cs,dotnet run app.cs,dotnet app.cs); if the arguments do not match, it falls back to the managed path. dotnet format app.csaccepts a file-based app, and with the SDK artifacts layout the outputs go under the repository's artifacts directory.dotnet referencesupports file-based apps:dotnet reference add --file app.cs <project-path>adds#:projectdirectives.dotnet run -e KEY=VALUEpasses environment variables to the launched app.
#:property Company="Contoso Tools"
#:property AssemblyTitle="Contoso Directive Demo"
#:package System.CommandLine@2.0.1 Aliases=CommandLine
extern alias CommandLine;
Console.WriteLine(typeof(CommandLine::System.CommandLine.RootCommand).Assembly.GetName().Name);
Run it with dotnet run Program.cs: the quoted value becomes the generated assembly's Company metadata.
How to enable it
The .NET 11 SDK is all you need: the source states no other settings for #:include.
The other C# 15 features
Collection expression arguments
A with(...) element as the first element of a collection expression passes arguments to the underlying collection's constructor or factory method: capacity, comparers or other parameters, right in the syntax.
string[] values = ["one", "two", "three"];
// Pass capacity argument to List<T> constructor
List<string> names = [with(capacity: values.Length * 2), .. values];
// Pass comparer argument to HashSet<T> constructor
HashSet<string> set = [with(StringComparer.OrdinalIgnoreCase), "Hello", "HELLO", "hello"];
// set contains only one element because all strings are equal with OrdinalIgnoreCase
Extension indexers
You can declare indexers in an extension block and index into the receiver as though the indexer were declared on its type. Because indexers are always instance members, the block must provide a named receiver parameter.
public static class SequenceIndexer
{
extension(IEnumerable<int> sequence)
{
public int this[int index] => sequence.ElementAt(index);
}
}
IEnumerable<int> numbers = Enumerable.Range(1, 10);
int third = numbers[2];
Labeled break and continue
These statements can name a label on an enclosing construct: break exits a loop or a switch, continue starts the next iteration of a loop. They replace the Boolean flags and goto statements used to steer out of nested loops; the IDE0410 style rule flags those patterns. Place the label directly on the loop or switch it identifies.
outer: for (int row = 0; row < grid.Height; row++)
{
for (int column = 0; column < grid.Width; column++)
{
if (grid[row, column].IsBlocked)
{
continue outer;
}
if (grid[row, column].IsGoal)
{
break outer;
}
}
}
Non-virtual static interface members on older runtimes
You can declare and use non-virtual static interface members even when the target runtime does not support default interface implementations. Call them directly on the interface, for example IMeasurement.ToMeters(250). Instance default implementations, static abstract and static virtual members, and protected interface members still require runtime support.
public interface IMeasurement
{
public static double ToMeters(double centimeters) => centimeters / 100;
}
Memory safety (preview feature)
This is the only C# 15 feature the source marks as preview: it requires <LangVersion>preview</LangVersion>, and for the updated rules also the updated-memory-safety-rules compiler feature flag. It starts a multirelease effort to tie the unsafe context to the operations that actually access unmanaged memory, rather than to the mere existence of pointer types. With the updated rules, unsafe on a member means the caller must use it from an unsafe context; a safe contextual keyword also appears for extern members and fields in explicit or extended layout types. With the preview language version, these no longer require an unsafe context: declaring a pointer type and taking an address with &, the fixed statement, converting stackalloc to a pointer, and sizeof on an unmanaged type. Dereferencing a pointer, pointer member or element access, and function pointer invocation still do. There is also an unsafe(expression) form that establishes an unsafe context for a single expression, useful where a block cannot appear, such as a field initializer:
class Header
{
// A field initializer can't contain an unsafe block, but it can contain an unsafe expression.
static readonly int Signature = unsafe(ReadSignature());
}
Unsafe expressions require the preview language version and the AllowUnsafeBlocks compiler option.
Summary table
| Paradigm | What is new | Where to read |
|---|---|---|
| Exclusive choices in data | Union types (union), JSON serialization, UnionAttribute/IUnion | C# 15, .NET 11 libraries |
| Hierarchies with exhaustiveness | closed classes | C# 15 |
| Asynchrony | Runtime Async (runtime-async=on) | .NET 11 runtime, dedicated article |
| Scripting and single files | #:include, directives with metadata, dotnet reference --file | .NET 11 SDK, dedicated article |
| Expressive syntax | with(...), extension indexers, labeled break/continue | C# 15, What's new in C# 15 |
| Memory safety | Updated unsafe rules (preview) | C# 15 |
How to try it
The source says to try C# 15 with the .NET 11 SDK or a compatible version of Visual Studio 2026. The official links to download .NET 11 are:
For the big picture of the release see the .NET 11 overview and downloads, and for unions in JSON also JSON, networking and security libraries. If you run into problems with the new features, the source suggests opening an issue in the dotnet/roslyn repository.
Sources
- What's new in C# 15
- What's new in .NET 11 runtime
- What's new in .NET 11 libraries
- What's new in the .NET 11 SDK
- What's new in .NET 11
- What's new in F# 11
Comments (0)
No comments yet.