Skip to content
Merged
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
10 changes: 9 additions & 1 deletion docs/csharp/fundamentals/functional/pattern-matching.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
title: Pattern matching overview
description: "Learn about pattern matching expressions in C#"
ms.date: 03/13/2024
ms.date: 01/27/2025
---

# Pattern matching overview
Expand Down Expand Up @@ -78,6 +78,14 @@ The first two arms examine two properties of the `Order`. The third examines onl

The preceding code demonstrates the [*positional pattern*](../../language-reference/operators/patterns.md#positional-pattern) where the properties are deconstructed for the expression.

You can also match a property against `{ }`, which matches any non-null value. Consider the following declaration, which stores measurements with an optional annotation:

:::code language="csharp" source="snippets/patterns/Program.cs" ID="Observation":::

You can test if a given observation has a non-null annotation using the following pattern matching expression:

:::code language="csharp" source="snippets/patterns/Program.cs" ID="NotNullPropertyPattern":::

## List patterns

You can check elements in a list or an array using a *list pattern*. A [list pattern](../../language-reference/operators/patterns.md#list-patterns) provides a means to apply a pattern to any element of a sequence. In addition, you can apply the *discard pattern* (`_`) to match any element, or apply a *slice pattern* to match zero or more elements.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@ static void Main(string[] args)

NullReferenceCheck();

var sequence = new List<int> {1,2,3,4,5,6,7};
var sequence = new List<int> { 1, 2, 3, 4, 5, 6, 7 };
var middle = MidPoint(sequence);
Console.WriteLine(middle);

ListPattern.Example();

NotNullProperty(new Observation(42, "C", "Temperature"));
}

// <MidPoint>
Expand Down Expand Up @@ -65,4 +67,21 @@ private static void NullCheck()
}
// </NullableCheck>
}

private static void NotNullProperty(Observation observation)
{
// <NotNullPropertyPattern>
if (observation.Annotation is { })
{
Console.WriteLine($"Observation description: {observation.Annotation}");
}
// </NotNullPropertyPattern>
}

// <Observation>
public record class Observation(int Value, string Units, string Name)
{
public string? Annotation { get; set; }
}
// </Observation>
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
Expand Down
Loading