LEARN BUILD GROW TOGETHER
DEVELOPER LEARNING HUB
Learn. Build. Grow Together.

Practical tutorials, real-world examples and interview preparation.

.NETC#SQL SERVERANGULAR
Home /.NET Developers /C# 15 New Features Explained With Code Examples

C# 15 New Features Explained With Code Examples

C# 15: New Language Features With Practical Examples | Skills Tutorials
SKILLS TUTORIALS · C# LANGUAGE GUIDE

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.

C# 15Language FeaturesPractical ExamplesDeveloper Guide

Learning Roadmap

Version context: C# 15 is the language version associated with the .NET 11 SDK. Except for the memory-safety preview, these features are not marked as preview in the current documentation. The examples below assume a compatible C# 15 compiler/SDK.

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.

Where it helps: When building collections from existing values and you know a capacity, or when you need to initialize collections with a comparer or other constructor options. Avoid adding a capacity estimate unless you have a reason for it.

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.

Where it helps: Modeling a result that may be one of several domain values—for example, a payment method, notification payload, or a message from a small set of known variants. Prefer a union to loosely typed 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.

Important: Closed hierarchies are not automatically closed transitively. If a descendant is itself extensible, it can have subclasses elsewhere. Mark intermediate classes 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.

Where it helps: Add convenient access patterns to types you don't own, when the semantics are clear and consistent. Remember that 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.

Where it helps: Search algorithms, grid or matrix processing, nested validation, and early-exit scenarios. Use labels sparingly and choose descriptive names so the control flow remains easy to follow.

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.

Where it helps: Shared conversions or small utilities that conceptually belong to a contract. This is not a replacement for instance members, and runtime support requirements still apply to other interface features such as default instance implementations and static virtual/abstract members.

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;
    }
}
Preview warning: Memory-safety syntax and compiler settings are subject to change. Use it only for experimentation and follow the current Microsoft documentation for enabling 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 continue and break in 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.
Learning approach: Run each snippet in the correct C# 15 environment. Some snippets are standalone demonstrations and may need to be placed in a console project or combined with the surrounding declarations. Keep one experiment per file while learning.

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.

Skills Tutorials
Learn • Build • Grow Together