C# 15: New Language Features With Practical Examples
Explore the latest C# language additions with runnable-style examples, understand why they matter, and see where they can improve everyday code. This guide focuses on C# language features—not .NET 11 framework or library updates.
Learning Roadmap
1. Collection Expression Arguments
Collection expressions already let you initialize collections using a
concise bracket syntax. C# 15 adds a with(...) element at
the start of a collection expression, allowing constructor or factory
arguments such as capacity or a comparer to be supplied inline.
Before: create the collection separately
var names = new List<string>(capacity: 20);
names.AddRange(sourceNames);
var users = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
users.Add("Alice");
users.Add("ALICE");
C# 15: configure while initializing
string[] sourceNames = ["Alice", "Bob", "Charlie"];
List<string> names = [with(capacity: sourceNames.Length * 2), .. sourceNames];
HashSet<string> users = [with(StringComparer.OrdinalIgnoreCase),
"Alice", "ALICE", "Bob"];
Console.WriteLine(names.Count); // 3
Console.WriteLine(users.Count); // 2
How it works: with(capacity: ...) supplies
a collection constructor argument, while
.. sourceNames spreads the existing values into the
collection. The comparer in the HashSet makes string
matching case-insensitive, so duplicate spellings collapse into one
entry.
2. Union Types
A union type represents a value that can be one of a defined set of case types. This is useful when a method can return different kinds of outcomes, and you want the allowed alternatives to be explicit in the type itself.
Define the possible 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);
class Program
{
static void Main()
{
Pet pet = new Dog("Rex");
string name = pet switch
{
Dog d => d.Name,
Cat c => c.Name,
Bird b => b.Name,
};
Console.WriteLine(name); // Rex
}
}
How it works: The union Pet declares three
possible cases. A value can be implicitly converted from one of those
case types into Pet. The switch expression handles each
case; the compiler can check that every union case is covered.
object results when the alternatives are
known.
3. Closed Hierarchies
The closed modifier limits where direct subclasses of a
class can be declared. This gives the compiler a known set of direct
descendants, enabling exhaustiveness checking in switch expressions for
that hierarchy.
public closed record class GateState;
public record class Closed : GateState;
public record class Open(float Percent) : GateState;
static string Describe(GateState state) => state switch
{
Closed => "Gate is closed",
Open(var percent) => $"Gate is {percent}% open",
};
Console.WriteLine(Describe(new Open(40))); // Gate is 40% open
How it works: Because GateState is closed,
its direct derived types must be declared in the same assembly. The
switch handles the two known direct cases. The compiler can warn if a
case is missing.
closed too
when you want exhaustiveness to continue through that level.
4. Extension Indexers
Extension indexers allow a type to be indexed using a member defined in
an extension declaration, without changing the original type. Here we
add an indexer to IEnumerable<int> that retrieves an
element by position.
using System.Collections.Generic;
using System.Linq;
public static class SequenceIndexer
{
extension(IEnumerable<int> sequence)
{
public int this[int index] => sequence.ElementAt(index);
}
}
IEnumerable<int> numbers = Enumerable.Range(10, 5);
int third = numbers[2];
Console.WriteLine(third); // 12
How it works: The extension declaration names the
receiver sequence. The indexer calls
ElementAt to retrieve the value at the requested position,
and the consuming code uses ordinary indexer syntax.
ElementAt on a general enumerable may require
iteration, so it isn't always constant-time like indexing an array or
list.
5. Labeled break and continue
Previously, a break or continue inside nested
loops targeted only the innermost loop. C# 15 lets you name an enclosing
loop label directly, making it easier to leave or continue an outer loop
without flags or jump workarounds.
int[,] grid =
{
{ 1, 2, 3 },
{ 4, 0, 6 },
{ 7, 8, 9 }
};
outer: for (int row = 0; row < grid.GetLength(0); row++)
{
for (int column = 0; column < grid.GetLength(1); column++)
{
if (grid[row, column] == 0)
continue outer; // skip to next row
if (grid[row, column] == 9)
break outer; // exit the outer loop
}
}
How it works: continue outer jumps to the
next iteration of the labeled outer loop, and
break outer exits that outer loop entirely. Unlabeled
statements retain their traditional innermost-loop behavior.
6. Non-virtual Static Interface Members on Older Runtimes
C# 15 supports non-virtual static interface members in cases where the target runtime doesn't support default interface implementations. This allows an interface to expose static helper logic without requiring every implementer to define that helper.
public interface IMeasurement
{
public static double ToMeters(double centimeters) => centimeters / 100;
}
class Program
{
static void Main()
{
double meters = IMeasurement.ToMeters(250);
Console.WriteLine(meters); // 2.5
}
}
How it works: The static method belongs to the interface and is called directly through the interface name. It's not a polymorphic instance member and implementing types don't need to provide their own version.
7. Memory Safety (Preview)
C# 15 starts a preview effort to make unsafe memory operations more explicit and easier to audit. The preview rules distinguish declaring pointer types and obtaining addresses from operations that actually dereference or access pointed-to memory. This feature is evolving and requires preview settings.
Preview example: take a variable's address
// Requires the C# 15 memory-safety preview settings.
int value = 42;
int* pointer = &value;
// Accessing pointed-to memory (dereferencing) still requires
// an unsafe context under the preview rules:
unsafe
{
Console.WriteLine(*pointer); // 42
}
How it works: With the preview language version, some
pointer declarations and address-taking operations can occur without
wrapping the whole block in unsafe. Operations such as
pointer dereference, pointer indexing, and pointer-member access still
require unsafe context.
Single-expression unsafe context
class Header
{
static readonly int Signature = unsafe(ReadSignature());
static unsafe int ReadSignature()
{
int raw = 0x1234;
int* p = &raw;
return *p;
}
}
LangVersion=preview, AllowUnsafeBlocks, and
the updated memory-safety feature flag.
Quick Comparison: What Problem Does Each Feature Solve?
| Feature | Primary benefit | Explore first when… |
|---|---|---|
| Collection expression arguments | Concise collection initialization with constructor arguments | You create lists, sets, or collections with capacity/comparer options |
| Union types | Express a value as one of several explicit cases | A method or domain value has multiple known alternatives |
| Closed hierarchies | Known direct subclasses and exhaustive switching | You model fixed state/result hierarchies |
| Extension indexers | Convenient indexer syntax on types you don't own | A type has a useful positional access pattern |
| Labeled break/continue | Clear control flow through nested loops | You need to skip or exit an outer loop |
| Static interface helpers | Shared helper logic on interfaces | A helper is conceptually part of a contract |
| Memory safety preview | More explicit unsafe boundaries and auditability | You work with pointers, interop, or low-level memory |
Try It Yourself: Mini Exploration Checklist
Use a small console project and test one feature at a time. Compare the new syntax with your existing approach, then decide whether it improves readability or maintainability.
-
Initialize a
List<string>with an explicit capacity using a collection expression. - Build a union type with two or three cases and handle all cases in a switch expression.
- Create a closed hierarchy and intentionally omit one case to observe compiler feedback.
- Write an extension indexer for a sequence and compare its performance with a list indexer.
-
Use labeled
continueandbreakin a nested loop; compare readability with a flag-based solution. - Call a non-virtual static interface helper without implementing it in a class.
- Try the memory-safety preview in a throwaway project only after reading the preview setup instructions.
Conclusion
C# 15 introduces new ways to model alternatives, initialize collections, express class hierarchies, add indexer behavior, and control nested loops. The static interface and memory-safety updates also expand language capabilities in specialized scenarios. The most useful way to learn these changes is to build small examples, inspect compiler behavior, and compare the new syntax with code you already write.
Official Microsoft References
C# 15 examples and feature descriptions are based on the official language documentation. Memory safety is marked preview; verify current compiler/SDK support before using it.