loading experience

.NET

What's new in C# 15: unions, closed and more

C# 15 with .NET 11: collection expression with(), union types, closed hierarchies, extension indexers, labeled break and continue, memory safety.

C# 15 ships with the .NET 11 SDK (or a compatible version of Visual Studio 2026) and brings seven features: collection expression arguments, union types, closed hierarchies, extension indexers, labeled break and continue, non-virtual static interface members on older runtimes and, as a preview, new memory safety rules. Here is what changes, with the examples from the official documentation.

Getting C# 15

  • C# 15 is the default language version for projects that target net11.0 in the .NET 11 SDK.
  • Only the memory safety preview feature requires <LangVersion>preview</LangVersion>.

Get the SDK from the .NET 11 download page.

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 inside the collection expression syntax.

string[] values = ["one", "two", "three"];
List<string> names = [with(capacity: values.Length * 2), .. values];
HashSet<string> set = [with(StringComparer.OrdinalIgnoreCase), "Hello", "HELLO", "hello"];
// set contains only one element

Union types

The union keyword declares a value that can be one of several case types. A union gets implicit conversions from each case type, and the compiler ensures that switch expressions are exhaustive across all the 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,
};

Closed hierarchies

The closed modifier on a class declares a closed hierarchy: the class can only be derived from within its declaring assembly, so the direct descendants are fixed at compile time. A switch expression that handles each one is exhaustive and needs no default arm.

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",
};
  • closed is a contextual keyword.
  • A closed class is implicitly abstract and can't be combined with sealed, static or an explicit abstract.
  • Derivation isn't transitive: a non-closed descendant can still be derived from in other assemblies. To extend exhaustiveness checking down the hierarchy, mark intermediate descendants closed too.

Extension indexers

An extension block can now declare indexers, so you can index into a receiver as though the indexer were declared on the receiver type. Indexers are always instance members, so 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

break and continue can name a label on an enclosing construct: a labeled break exits an enclosing loop or switch, a labeled continue starts the next iteration of an enclosing loop. They replace the Boolean flags or goto jumps you would otherwise use to steer control flow through nested loops. Put the label directly on the loop or switch it identifies; without a label, the statements behave as before. The IDE0410 style rule flags the flag and goto patterns that a labeled jump can replace.

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

Starting in C# 15 you can declare and use non-virtual static interface members even when the target runtime doesn't support default interface implementations. Call the helper directly on the interface, for example IMeasurement.ToMeters(250).

public interface IMeasurement
{
    public static double ToMeters(double centimeters) => centimeters / 100;
}
// IMeasurement.ToMeters(250)

Instance default implementations, static abstract and static virtual members, and protected interface members still require runtime support.

Memory safety (preview)

The .NET 11 SDK includes a memory safety preview feature that starts a multirelease effort to redefine memory safety: the unsafe context is tied to the operations that actually access unmanaged memory, rather than to the existence of pointer types. With the updated rules, unsafe on a member marks it as requires-unsafe and the audit obligation flows to the caller. The compiler records the use of the rules with MemorySafetyRulesAttribute, and a new safe contextual keyword marks 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 any unmanaged type.

int number = 42;
int* pointer = &number;

int[] numbers = [10, 20, 30];
fixed (int* first = numbers)
{
    // Dereferencing the pointer still requires an unsafe context.
}

Pointer indirection (*p), member access (p->member), element access (p[i]) and function pointer invocation still require an unsafe context. C# 15 also adds the unsafe(expression) expression, handy where an unsafe block can't appear, such as a field initializer, a constructor initializer or a catch filter:

class Header
{
    static readonly int Signature = unsafe(ReadSignature());

    static unsafe int ReadSignature()
    {
        unsafe
        {
            int rawValue = 0x1234;
            int* pointer = &rawValue;
            return *pointer;
        }
    }
}

Unsafe expressions require the preview language version and the AllowUnsafeBlocks option. To also enable the updated rules, turn on the updated-memory-safety-rules compiler feature.

Sources

Comments (0)

No comments yet.

Leave a comment