Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 34 additions & 1 deletion docs/csharp/fundamentals/patterns/type-patterns.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
title: "Type patterns"
description: Learn when to use a C# type pattern for a yes-or-no run-time type test without declaring a variable.
ms.date: 09/15/2026
ms.date: 10/27/2026
ms.topic: concept-article
ai-usage: ai-assisted
---
Expand Down Expand Up @@ -44,6 +44,39 @@ Each arm answers a type question and returns the queue that handles that request

Switch arms are considered from top to bottom. Put a specialized class before its base class. Otherwise, the base-class arm can match every instance of the specialized class, which makes the later arm unreachable.

## Exhaustive matching with closed hierarchies

Starting in C# 15 (.NET 11), when the base class is declared with the [`closed`](../../language-reference/keywords/closed.md) modifier, the compiler knows every possible direct subtype within the declaring assembly. If a `switch` expression covers every direct derived type, the pattern match is *exhaustive* and does not require a fallback discard arm (`_`):

```csharp
public closed class Shape;

public sealed class Circle(double radius) : Shape
{
public double Radius { get; } = radius;
}

public sealed class Rectangle(double width, double height) : Shape
{
public double Width { get; } = width;
public double Height { get; } = height;
}

double CalculateArea(Shape shape) => shape switch
{
Circle c => Math.PI * c.Radius * c.Radius,
Rectangle r => r.Width * r.Height
// Exhaustive: every direct subtype of Shape is handled
};
```

The `closed` modifier applies to direct derivation. If all direct subtypes are `sealed`, the hierarchy is closed to all further derivation. If a direct subtype isn't `sealed`, derived leaf types can be declared, but an arm matching the direct subtype also matches any of its derived subtypes.

Adding a new direct subtype to a closed hierarchy is both a source and binary breaking change for consuming code:

- **Compile time**: When dependent code is recompiled against the updated hierarchy, the compiler issues a warning for any `switch` expression that no longer covers all direct subtypes.
- **Runtime**: If dependent code is run without being recompiled, any unhandled direct subtype that reaches an impacted `switch` expression throws a <xref:System.Runtime.CompilerServices.SwitchExpressionException> at run time.

## Optional: use a type parameter as the tested type

This optional example builds on [generic types and methods](../types/generics.md). A *type parameter* such as `TRequest` is a placeholder for a type that the caller supplies. An incoming-request batch can contain several request types, and the caller supplies `ConfidentialRequest` to test whether any request requires confidential handling. The Boolean result selects confidential handling for the entire batch and produces a visible status message. A type pattern with a type parameter fits because only the existence of a matching request matters, so the matching object doesn't need to be retained.
Expand Down
49 changes: 49 additions & 0 deletions docs/csharp/fundamentals/types/classes.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,55 @@ Classes support *inheritance*. You can define a new class that reuses, extends,

A class can inherit from one base class and implement multiple interfaces. Derived classes inherit all members of the base class except constructors. For more information, see [Inheritance](../object-oriented/inheritance.md) and [Interfaces](interfaces.md).

## Closed hierarchies

Starting in C# 15 (.NET 11), you can mark an inheritance base class with the [`closed`](../../language-reference/keywords/closed.md) modifier to declare a *closed hierarchy*. A `closed` class restricts direct derivation to the assembly in which the class is declared:

```csharp
public closed class PaymentMethod;
public class CreditCard(string Number) : PaymentMethod;
public class BankTransfer(string Iban) : PaymentMethod;
public class Cash : PaymentMethod;
```

A `closed` class serves as a polymorphic base type that provides shared behavior, properties, or virtual members across its direct subtypes while ensuring that code inspecting an instance can account for all possible forms.

### Direct subtypes vs. leaf types

A closed hierarchy guarantees that the compiler knows every *direct* subtype of the base class. However, how derivation behaves beyond those direct subtypes depends on whether the subtypes themselves are `sealed`:

- **Closed to all derivation**: If all direct subtypes are marked with the `sealed` modifier, the hierarchy is fully closed. No further derived classes can be created anywhere:

```csharp
public closed class PaymentMethod;
public sealed class CreditCard(string Number) : PaymentMethod;
public sealed class BankTransfer(string Iban) : PaymentMethod;
public sealed class Cash : PaymentMethod;
```

- **Open leaf types**: If a direct subtype isn't `sealed`, other classes can inherit from it. The closed hierarchy still represents *all* direct subtypes, but not *all possible leaf types*. Pattern-matching a direct subtype matches both that subtype and any classes derived from it:

```csharp
public closed class PaymentMethod;
public class CreditCard(string Number) : PaymentMethod; // Non-sealed: can be extended
public class RewardsCreditCard(string Number, int Points) : CreditCard(Number); // Leaf type
public sealed class BankTransfer(string Iban) : PaymentMethod;
public sealed class Cash : PaymentMethod;
```

Because the complete set of direct descendants is fixed at compile time, the compiler verifies that pattern-matching `switch` expressions exhaustively cover all direct subtypes without needing a default or discard arm:

```csharp
decimal GetProcessingFee(PaymentMethod method) => method switch
{
CreditCard => 1.50m, // Matches CreditCard and RewardsCreditCard
BankTransfer => 0.50m,
Cash => 0.00m
};
```

For more information, see the [closed modifier](../../language-reference/keywords/closed.md) reference.

## See also

- [Type system overview](index.md)
Expand Down
4 changes: 2 additions & 2 deletions docs/csharp/fundamentals/types/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ C# provides [built-in types](built-in-types.md) for common data: integers, float

Beyond built-in types, you can create your own types by using several constructs:

- [**Classes**](classes.md) — Reference types for modeling behavior and complex objects. Support inheritance and polymorphism.
- [**Classes**](classes.md) — Reference types for modeling behavior and complex objects. Support inheritance, polymorphism, and [closed hierarchies](classes.md#closed-hierarchies).
- [**Structs**](structs.md) — Value types for small, lightweight data. Each variable holds its own copy.
- [**Records**](records.md) — Classes or structs with compiler-generated equality, `ToString`, and nondestructive mutation through `with` expressions.
- [**Interfaces**](interfaces.md) — Contracts that define members any class or struct can implement.
Expand Down Expand Up @@ -70,7 +70,7 @@ When you define a new type, the kind you choose shapes how your code behaves. Us
- **Tuple** — Temporary grouping of values that doesn't need a named type or behavior.
- **`struct`** or **`record struct`** — Small data (roughly 64 bytes or less), value semantics, or immutability. Record structs add value-based equality and `with` expressions.
- **`record class`** — Primarily data, with value-based equality, `ToString`, and nondestructive mutation. Supports inheritance.
- **`class`** — Complex behavior, polymorphism, or mutable state. Most custom types are classes.
- **`class`** — Complex behavior, polymorphism, or mutable state. Most custom types are classes. Use `closed class` or `closed record class` when defining a closed set of subtypes for exhaustive pattern matching.
- **`interface`** — A contract that unrelated types can implement. Defines capabilities rather than identity.
- **`enum`** — A fixed set of named constants, such as status codes or options.

Expand Down
24 changes: 24 additions & 0 deletions docs/csharp/fundamentals/types/records.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,30 @@ A `record class` can inherit from another `record class`. A record can't inherit

Value equality checks include the run-time type, so a `Person` and a `Student` with the same `FirstName` and `LastName` aren't considered equal. Record structs don't support inheritance because structs can't inherit from other types.

### Closed record hierarchies

Starting in C# 15 (.NET 11), combining the [`closed`](../../language-reference/keywords/closed.md) modifier with `record class` creates a closed algebraic hierarchy where each variant is represented by a concise record:

```csharp
public closed record class Result<T>;
public sealed record class Success<T>(T Value) : Result<T>;
public sealed record class Failure<T>(string Error) : Result<T>;
```

Marking each direct subtype `sealed` closes the hierarchy completely against further derivation, ensuring that the hierarchy defines all possible leaf types. If any direct subtype is left unsealed, other record types could extend it, meaning the hierarchy would define all direct subtypes, but not necessarily all leaf types.

Because `Result<T>` is `closed`, consumers can match on all variants without needing a fallback discard pattern:

```csharp
string FormatResult<T>(Result<T> result) => result switch
{
Success<T> s => $"Success: {s.Value}",
Failure<T> f => $"Failure: {f.Error}"
};
```

This pattern provides a powerful alternative to [union types](../../language-reference/builtin-types/union.md) when you want compiler-generated value equality, `ToString`, and positional deconstruction across a fixed set of reference types.

## See also

- [Type system overview](index.md)
Expand Down