## Executive Summary

Dustin Campbell and Mads Torgersen dive deep into the flagship language features introduced in **C# 15** for .NET 11. While the headline announcement is **Discriminated Unions**, C# 15 delivers a complete wave of type-safety and developer ergonomic enhancements:
1. **First-Class Discriminated Unions:** Formal `union` type declarations enabling ad-hoc disjoint union sets with implicit widening conversions and exhaustive pattern matching.
2. **Low-Level Union Customization & `IUnion`:** Defining custom struct/class unions with `[Union]`, custom constructors, and non-boxing storage for high-throughput scenarios.
3. **Closed Classes (`closed class`):** Restricting class inheritance strictly to the declaring assembly, unlocking compile-time exhaustiveness guarantees across object-oriented class hierarchies.
4. **Collection Expressions with Arguments (`[with(...) ...]`):** Passing custom arguments (such as `IEqualityComparer<T>` or initial capacity) directly to collection expression initializers.
5. **Labeled `break` and `continue`:** Cleanly exiting or resuming nested loops without boolean flags or `goto`.
6. **Extension Indexers:** Extending C# 14's extension block syntax to support indexer definitions (`this[int index]`).
7. **Safe Unsafe & Runtime Async:** Deep compiler/CLR runtime integration bringing zero-allocation synchronous async paths and transitive unsafe tracking.

---

## Detailed Section-by-Section Breakdown

### 1. Discriminated Unions (`union`)

**Presenters:** Dustin Campbell & Mads Torgersen

For years, grouping unrelated types (e.g., `Dog`, `Cat`, `Bird` originating from disparate third-party libraries) forced developers to fall back to `object` or artificial base interfaces. This introduced risks: unwanted types (like `Shark`) could slip in, and switch expressions required awkward catch-all/discard arms (`_ => ...`), suppressing compiler exhaustiveness warnings.

#### Syntax & Core Rules:
```csharp
public union Pet = Dog | Cat | Bird;
```

- **Case Types:** `Dog`, `Cat`, and `Bird` are designated case types of `Pet`.
- **Implicit Conversion:** Any case type can be assigned to the union without explicit casting:
  ```csharp
  Pet pet = new Dog(); // Implicitly converted to Pet
  ```
- **Type Safety Gate:** Non-case types (e.g. `Shark`) cause compiler errors at compile time when attempting assignment or pattern matching.
- **Exhaustive Pattern Matching:** The compiler checks that all cases are handled in `switch` expressions. Once all cases are present, no fallback discard arm is required.

![C# 15 Unions Syntax and Type Safety](/dotnetconf2026/archive/03-whats-new-in-csharp/screenshots/01_csharp15_unions_syntax.webp)

---

### 2. Nullable Case Handling & Compiler Feedback

If a union includes a nullable case type (e.g., `Cat?`), the compiler immediately flags switch expressions that do not handle `null`.

```csharp
public union Pet = Dog | Cat? | Bird;

string mood = pet switch
{
    Dog d => "Loyal dog",
    Cat c => "Playful cat",
    null  => "Missing cat (null)",
    Bird b => "Singing bird"
};
```

The Roslyn diagnostic specifically guides developers to handle the missing `null` case, preventing runtime `NullReferenceException` surprises.

![Handling Nullable Union Cases and Exhaustiveness](/dotnetconf2026/archive/03-whats-new-in-csharp/screenshots/02_unions_nullable_exhaustiveness.webp)

---

### 3. Adding Members and Custom Functionality to Unions

Unions are full-fledged type definitions. In addition to the short-form semicolon declaration, developers can provide a body enclosed in braces to define methods, computed properties, and helper logic:

```csharp
public union Pet = Dog | Cat | Bird
{
    public string Sound => this switch
    {
        Dog => "Woof",
        Cat => "Meow",
        Bird => "Chirp"
    };
}
```

> [!NOTE]
> Additional instance fields or mutable state cannot be declared inside a union body; the value stored within the union constitutes its entire state.

![Adding Custom Helper Members to Unions](/dotnetconf2026/archive/03-whats-new-in-csharp/screenshots/03_unions_custom_members.webp)

---

### 4. Low-Level Mechanics: Manual Unions, `[Union]`, and `IUnion`

The default compiler implementation generates an efficient struct representation. For advanced scenarios—such as preventing boxing when storing value types, or wrapping existing domain types—developers can hand-author a union:

1. Decorate a `struct` or `class` with `[Union]`.
2. Implement `IUnion` (exposing `object? Value { get; }`).
3. Define constructors taking each permitted case type.

```csharp
[Union]
public readonly struct Pet : IUnion
{
    public object? Value { get; }

    public Pet(Dog dog) => Value = dog;
    public Pet(Cat cat) => Value = cat;
    public Pet(Bird bird) => Value = bird;
}
```

The compiler recognizes this pattern, enabling implicit conversions and pattern matching identically to the concise `union` syntax, while giving high-performance libraries control over internal memory layout.

![Low-Level Union Struct Implementation and IUnion](/dotnetconf2026/archive/03-whats-new-in-csharp/screenshots/04_unions_low_level_struct_iunion.webp)

---

### 5. Closed Classes (`closed class`)

While unions group heterogeneous types, object-oriented domain models often rely on class hierarchies (e.g., an abstract syntax tree or calculator operations: `Operation` with `Number`, `Add`, `Subtract`, `Multiply`, `Divide`).

In public libraries, an `abstract class` can be subclassed by external assemblies, making exhaustive pattern matching impossible without a discard arm.

C# 15 introduces **`closed class`**:
```csharp
public closed class Operation { }

public class Number(double val) : Operation { }
public class Add(Operation left, Operation right) : Operation { }
public class Subtract(Operation left, Operation right) : Operation { }
```

#### Key Characteristics:
- Automatically marks the class as abstract.
- **Enforces assembly-internal inheritance:** Only classes defined within the same assembly can derive from `Operation`.
- **External compilation error:** If an external consumer attempts to derive from `Operation`, Roslyn produces a compile error.
- **Exhaustive Matching:** Pattern switches within the defining assembly are verified for exhaustiveness by the compiler without requiring defensive fallback branches.

![Closed Classes for Exhaustive Class Hierarchies](/dotnetconf2026/archive/03-whats-new-in-csharp/screenshots/05_closed_classes_exhaustiveness.webp)

---

### 6. Collection Expressions with Constructor Arguments (`with`)

C# 12 introduced collection expressions (`[1, 2, 3]`). However, when developers needed to pass initialization arguments—such as an `IEqualityComparer<T>` to a `HashSet<string>` or an initial capacity to a `List<T>`—they were forced to fall back to `new HashSet<string>(comparer) { ... }`.

C# 15 extends collection expressions with the `with` argument prefix:

```csharp
HashSet<string> names = [with(StringComparer.OrdinalIgnoreCase) "Alice", "Bob", "Charlie"];
List<int> numbers = [with(capacity: 100) 1, 2, 3];
```

This retains the clean bracket syntax while passing constructor arguments to the underlying collection type.

![Collection Expressions with Arguments](/dotnetconf2026/archive/03-whats-new-in-csharp/screenshots/06_collection_expressions_with_arguments.webp)

---

### 7. Labeled `break` and `continue`

Escaping nested loops previously required declaring state flags (e.g. `bool isDone = false;`) or resorting to `goto`. C# 15 adds labeled jump statements:

```csharp
outer:
for (int i = 0; i < matrix.Length; i++)
{
    for (int j = 0; j < matrix[i].Length; j++)
    {
        if (matrix[i][j] == target)
        {
            break outer; // Directly breaks out of the outer loop
        }
    }
}
```

This significantly clarifies multi-dimensional search loops and reduces boilerplate state tracking.

![Labeled Break and Continue](/dotnetconf2026/archive/03-whats-new-in-csharp/screenshots/07_labeled_break_continue.webp)

---

### 8. Extension Indexers

Expanding upon C# 14's unified `extension` group syntax, C# 15 allows declaring custom indexers:

```csharp
public static class ListExtensions
{
    extension<T>(IList<T> list)
    {
        public T this[Index index] => list[index.GetOffset(list.Count)];
    }
}
```

By defining the receiver once at the extension block level, regular C# member syntax—including methods, properties, and indexers—can be declared consistently.

![Extension Indexers](/dotnetconf2026/archive/03-whats-new-in-csharp/screenshots/08_extension_indexers.webp)

---

### 9. C# 15 Feature Summary & Runtime Synergy

The session concluded with an overview of how C# 15 and the .NET 11 runtime work in tandem:

- **Safer Unsafe:** Enhanced compiler checks track unsafe pointers and buffers transitively, allowing developers to create custom unsafe boundary abstractions with Rust-like rigor.
- **Runtime Async:** As demonstrated in the keynote, runtime async intrinsics eliminate state machines on synchronous paths for zero allocations.

![C# 15 Features Summary](/dotnetconf2026/archive/03-whats-new-in-csharp/screenshots/09_csharp15_features_summary_slide.webp)
