Skip to content

Commit d94f820

Browse files
BillWagnergfoidlgewarren
authored
Add introductory interactive pattern matching tutorial (#45954)
* First pass at the code. * update code for try.net restrictions * Apply suggestions from code review Co-authored-by: Günther Foidl <gue@korporal.at> * fix warnings * Move some code. * make a clone * Finish the switch example. * finish samples * fix warnings * typo * Finish article draft. * proofread * fix warnings * Apply suggestions from code review Co-authored-by: Genevieve Warren <24882762+gewarren@users.noreply.github.com> * add new tutorial to TOC --------- Co-authored-by: Günther Foidl <gue@korporal.at> Co-authored-by: Genevieve Warren <24882762+gewarren@users.noreply.github.com>
1 parent 89c8783 commit d94f820

File tree

8 files changed

+376
-1
lines changed

8 files changed

+376
-1
lines changed

docs/csharp/toc.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ items:
1919
href: tour-of-csharp/tutorials/branches-and-loops.md
2020
- name: List collections
2121
href: tour-of-csharp/tutorials/list-collection.md
22+
- name: Pattern matching
23+
href: tour-of-csharp/tutorials/pattern-matching.md
2224
- name: C# language strategy
2325
href: tour-of-csharp/strategy.md
2426
- name: Learn C# for Java developers

docs/csharp/tour-of-csharp/tutorials/index.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
title: Interactive tutorials
33
description: Learn C# in your browser, and get started with your own development environment
4-
ms.date: 03/20/2025
4+
ms.date: 04/23/2025
55
---
66
# Introduction to C\#
77

@@ -37,6 +37,10 @@ The [Branches and loops](branches-and-loops.md) tutorial teaches the basics of s
3737

3838
The [List collection](list-collection.md) lesson gives you a tour of the List collection type that stores sequences of data. You'll learn how to add and remove items, search for items, and sort the lists. You'll explore different kinds of lists.
3939

40+
## Pattern matching
41+
42+
The [Pattern matching](pattern-matching.md) lesson provides an introduction to *pattern matching*. Pattern matching enables you to compare an expression against a pattern. The success of the match determines which program logic to follow. Patterns can compare types, properties of a type, or contents of a list. You can combine multiple patterns using `and`, `or`, and `not` logic. Patterns provide a rich vocabulary to inspect data and make decisions in your program based on that inspection.
43+
4044
## Set up your local environment
4145

4246
After you finish these tutorials, set up a development environment. You'll want:
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
---
2+
title: Pattern matching
3+
description: In this tutorial about pattern matching, you use your browser to learn C# interactively. You're going to write C# code and see the results of compiling and running your code directly in the browser.
4+
ms.date: 05/02/2025
5+
---
6+
# Match data against patterns
7+
8+
This tutorial teaches you how to use pattern matching to inspect data in C#. You write small amounts of code, then you compile and run that code. The tutorial contains a series of lessons that explore different kinds of types in C#. These lessons teach you the fundamentals of the C# language.
9+
10+
> [!TIP]
11+
> When a code snippet block includes the "Run" button, that button opens the interactive window, or replaces the existing code in the interactive window. When the snippet doesn't include a "Run" button, you can copy the code and add it to the current interactive window.
12+
13+
The preceding tutorials demonstrated built-in types and types you define as tuples or records. Instances of these types can be checked against a *pattern*. Whether an instance matches a pattern determines the actions your program takes. Let's start to explore how you can use patterns.
14+
15+
## Match a value
16+
17+
All the examples in this tutorial use text input that represents a series of bank transactions as comma separated values (CSV) input. In each of the samples you can match the record against a pattern using either an `is` or `switch` expression. This first example splits each line on the `,` character and then *matches* the first string field against the value "DEPOSIT" or "WITHDRAWAL" using an `is` expression. When it matches, the transaction amount is added or deducted from the current account balance. To see it work, press the "Run" button:
18+
19+
:::code language="csharp" interactive="try-dotnet-method" source="./snippets/PatternMatching/Program.cs" id="FirstExample":::
20+
21+
Examine the output. You can see that each line is processed by comparing the value of the text in the first field. The preceding sample could be similarly constructed using the `==` operator to test that two `string` values are equal. Comparing a variable to a constant is a basic building block for pattern matching. Let's explore more of the building blocks that are part of pattern matching.
22+
23+
## Enum matches
24+
25+
Another common use for pattern matching is to match on the values of an `enum` type. This next sample processes the input records to create a *tuple* where the first value is an `enum` value that notes a deposit or a withdrawal. The second value is the value of the transaction. To see it work, press the "Run" button:
26+
27+
> [!WARNING]
28+
> Don't copy and paste. The interactive window must be reset to run the following samples. If you make a mistake, the window hangs, and you need to refresh the page to continue.
29+
30+
:::code language="csharp" interactive="try-dotnet" source="./snippets/PatternMatching/FirstEnumExample.cs" id="IsEnumValue":::
31+
32+
The preceding example also uses an `if` statement to check the value of an `enum` expression. Another form of pattern matching uses a `switch` expression. Let's explore that syntax and how you can use it.
33+
34+
## Exhaustive matches with `switch`
35+
36+
A series of `if` statements can test a series of conditions. But, the compiler can't tell if a series of `if` statements are *exhaustive* or if later `if` conditions are *subsumed* by earlier conditions. The `switch` expression ensures both of those characteristics are met, which results in fewer bugs in your apps. Let's try it and experiment. Copy the following code. Replace the two `if` statements in the interactive window with the `switch` expression you copied. After you've modified the code, press the "Run" button at the top of the interactive window to run the new sample.
37+
38+
:::code language="csharp" interactive="try-dotnet" source="./snippets/PatternMatching/EnumSwitchExample.cs" id="SwitchEnumValue":::
39+
40+
When you run the code, you see that it works the same. To demonstrate *subsumption*, reorder the switch arms as shown in the following snippet:
41+
42+
```csharp
43+
currentBalance += transaction switch
44+
{
45+
(TransactionType.Deposit, var amount) => amount,
46+
_ => 0.0,
47+
(TransactionType.Withdrawal, var amount) => -amount,
48+
};
49+
```
50+
51+
After you reorder the switch arms, press the "Run" button. The compiler issues an error because the arm with `_` matches every value. As a result, that final arm with `TransactionType.Withdrawal` never runs. The compiler tells you that something's wrong in your code.
52+
53+
The compiler issues a warning if the expression tested in a `switch` expression could contain values that don't match any switch arm. If some values could fail to match any condition, the `switch` expression isn't *exhaustive*. The compiler also issues a warning if some values of the input don't match any of the switch arms. For example, if you remove the line with `_ => 0.0,`, any invalid values don't match. At run time, that would fail. Once you install the .NET SDK and build programs in your environment, you can test this behavior. The online experience doesn't display warnings in the output window.
54+
55+
## Type patterns
56+
57+
To finish this tutorial, let's explore one more building block to pattern matching: the *type pattern*. A *type pattern* tests an expression at run time to see if it's the specified type. You can use a type test with either an `is` expression or a `switch` expression. Let's modify the current sample in two ways. First, instead of a tuple, let's build `Deposit` and `Withdrawal` record types that represent the transactions. Add the following declarations at the bottom of the interactive window:
58+
59+
:::code language="csharp" interactive="try-dotnet" source="./snippets/PatternMatching/FinalExampleProgram.cs" id="RecordDeclarations":::
60+
61+
Next, add this method after the `Main` method to parse the text and return a series of records:
62+
63+
:::code language="csharp" interactive="try-dotnet" source="./snippets/PatternMatching/FinalExampleProgram.cs" id="ParseToRecord":::
64+
65+
Finally, replace the `foreach` loop in the `Main` method with the following code:
66+
67+
:::code language="csharp" interactive="try-dotnet" source="./snippets/PatternMatching/FinalExampleProgram.cs" id="TypePattern":::
68+
69+
Then, press the "Run" button to see the results. This final version tests the input against a *type*.
70+
71+
Pattern matching provides a vocabulary to compare an expression against characteristics. Patterns can include the expression's type, values of types, property values, and combinations of them. Comparing expressions against a pattern can be more clear than multiple `if` comparisons. You explored some of the patterns you can use to match expressions. There are many more ways to use pattern matching in your applications. First, visit the [.NET site](https://dotnet.microsoft.com/learn/dotnet/hello-world-tutorial/intro) to download the .NET SDK, create a project on your machine, and keep coding. As you explore, you can learn more about pattern matching in C# in the following articles:
72+
73+
- [Pattern matching in C#](../../fundamentals/functional/pattern-matching.md)
74+
- [Explore pattern matching tutorial](../../tutorials/patterns-objects.md)
75+
- [Pattern matching scenario](../../fundamentals/tutorials/pattern-matching.md)
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
namespace EnumSwitchExample;
2+
3+
// <IsEnumValue>
4+
public static class ExampleProgram
5+
{
6+
const string bankRecords = """
7+
DEPOSIT, 10000, Initial balance
8+
DEPOSIT, 500, regular deposit
9+
WITHDRAWAL, 1000, rent
10+
DEPOSIT, 2000, freelance payment
11+
WITHDRAWAL, 300, groceries
12+
DEPOSIT, 700, gift from friend
13+
WITHDRAWAL, 150, utility bill
14+
DEPOSIT, 1200, tax refund
15+
WITHDRAWAL, 500, car maintenance
16+
DEPOSIT, 400, cashback reward
17+
WITHDRAWAL, 250, dining out
18+
DEPOSIT, 3000, bonus payment
19+
WITHDRAWAL, 800, loan repayment
20+
DEPOSIT, 600, stock dividends
21+
WITHDRAWAL, 100, subscription fee
22+
DEPOSIT, 1500, side hustle income
23+
WITHDRAWAL, 200, fuel expenses
24+
DEPOSIT, 900, refund from store
25+
WITHDRAWAL, 350, shopping
26+
DEPOSIT, 2500, project milestone payment
27+
WITHDRAWAL, 400, entertainment
28+
""";
29+
30+
public static void Main()
31+
{
32+
double currentBalance = 0.0;
33+
34+
foreach (var transaction in TransactionRecords(bankRecords))
35+
{
36+
// <SwitchEnumValue>
37+
currentBalance += transaction switch
38+
{
39+
(TransactionType.Deposit, var amount) => amount,
40+
(TransactionType.Withdrawal, var amount) => -amount,
41+
_ => 0.0,
42+
};
43+
// </SwitchEnumValue>
44+
Console.WriteLine($"{transaction.type} => Parsed Amount: {transaction.amount}, New Balance: {currentBalance}");
45+
}
46+
}
47+
48+
static IEnumerable<(TransactionType type, double amount)> TransactionRecords(string inputText)
49+
{
50+
var reader = new StringReader(inputText);
51+
string? line;
52+
while ((line = reader.ReadLine()) is not null)
53+
{
54+
string[] parts = line.Split(',');
55+
56+
string? transactionType = parts[0]?.Trim();
57+
if (double.TryParse(parts[1].Trim(), out double amount))
58+
{
59+
// Update the balance based on transaction type
60+
if (transactionType?.ToUpper() is "DEPOSIT")
61+
yield return (TransactionType.Deposit, amount);
62+
else if (transactionType?.ToUpper() is "WITHDRAWAL")
63+
yield return (TransactionType.Withdrawal, amount);
64+
}
65+
yield return (TransactionType.Invalid, 0.0);
66+
}
67+
}
68+
}
69+
70+
public enum TransactionType
71+
{
72+
Deposit,
73+
Withdrawal,
74+
Invalid
75+
}
76+
// </IsEnumValue>
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
public static class ExampleProgram
2+
{
3+
const string bankRecords = """
4+
DEPOSIT, 10000, Initial balance
5+
DEPOSIT, 500, regular deposit
6+
WITHDRAWAL, 1000, rent
7+
DEPOSIT, 2000, freelance payment
8+
WITHDRAWAL, 300, groceries
9+
DEPOSIT, 700, gift from friend
10+
WITHDRAWAL, 150, utility bill
11+
DEPOSIT, 1200, tax refund
12+
WITHDRAWAL, 500, car maintenance
13+
DEPOSIT, 400, cashback reward
14+
WITHDRAWAL, 250, dining out
15+
DEPOSIT, 3000, bonus payment
16+
WITHDRAWAL, 800, loan repayment
17+
DEPOSIT, 600, stock dividends
18+
WITHDRAWAL, 100, subscription fee
19+
DEPOSIT, 1500, side hustle income
20+
WITHDRAWAL, 200, fuel expenses
21+
DEPOSIT, 900, refund from store
22+
WITHDRAWAL, 350, shopping
23+
DEPOSIT, 2500, project milestone payment
24+
WITHDRAWAL, 400, entertainment
25+
""";
26+
27+
public static void Main()
28+
{
29+
double currentBalance = 0.0;
30+
31+
// <TypePattern>
32+
foreach (var transaction in TransactionRecordType(bankRecords))
33+
{
34+
currentBalance += transaction switch
35+
{
36+
Deposit d => d.Amount,
37+
Withdrawal w => -w.Amount,
38+
_ => 0.0,
39+
};
40+
Console.WriteLine($" {transaction} => New Balance: {currentBalance}");
41+
}
42+
// </TypePattern>
43+
}
44+
45+
// <ParseToRecord>
46+
public static IEnumerable<object?> TransactionRecordType(string inputText)
47+
{
48+
var reader = new StringReader(inputText);
49+
string? line;
50+
while ((line = reader.ReadLine()) is not null)
51+
{
52+
string[] parts = line.Split(',');
53+
54+
string? transactionType = parts[0]?.Trim();
55+
if (double.TryParse(parts[1].Trim(), out double amount))
56+
{
57+
// Update the balance based on transaction type
58+
if (transactionType?.ToUpper() is "DEPOSIT")
59+
yield return new Deposit(amount, parts[2]);
60+
else if (transactionType?.ToUpper() is "WITHDRAWAL")
61+
yield return new Withdrawal(amount, parts[2]);
62+
}
63+
yield return default;
64+
}
65+
}
66+
// </ParseToRecord>
67+
}
68+
69+
public enum TransactionType
70+
{
71+
Deposit,
72+
Withdrawal,
73+
Invalid
74+
}
75+
76+
// <RecordDeclarations>
77+
public record Deposit(double Amount, string description);
78+
public record Withdrawal(double Amount, string description);
79+
// </RecordDeclarations>
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
namespace FirstEnumExample;
2+
3+
// <IsEnumValue>
4+
public static class ExampleProgram
5+
{
6+
const string bankRecords = """
7+
DEPOSIT, 10000, Initial balance
8+
DEPOSIT, 500, regular deposit
9+
WITHDRAWAL, 1000, rent
10+
DEPOSIT, 2000, freelance payment
11+
WITHDRAWAL, 300, groceries
12+
DEPOSIT, 700, gift from friend
13+
WITHDRAWAL, 150, utility bill
14+
DEPOSIT, 1200, tax refund
15+
WITHDRAWAL, 500, car maintenance
16+
DEPOSIT, 400, cashback reward
17+
WITHDRAWAL, 250, dining out
18+
DEPOSIT, 3000, bonus payment
19+
WITHDRAWAL, 800, loan repayment
20+
DEPOSIT, 600, stock dividends
21+
WITHDRAWAL, 100, subscription fee
22+
DEPOSIT, 1500, side hustle income
23+
WITHDRAWAL, 200, fuel expenses
24+
DEPOSIT, 900, refund from store
25+
WITHDRAWAL, 350, shopping
26+
DEPOSIT, 2500, project milestone payment
27+
WITHDRAWAL, 400, entertainment
28+
""";
29+
30+
public static void Main()
31+
{
32+
double currentBalance = 0.0;
33+
34+
foreach (var transaction in TransactionRecords(bankRecords))
35+
{
36+
if (transaction.type == TransactionType.Deposit)
37+
currentBalance += transaction.amount;
38+
else if (transaction.type == TransactionType.Withdrawal)
39+
currentBalance -= transaction.amount;
40+
Console.WriteLine($"{transaction.type} => Parsed Amount: {transaction.amount}, New Balance: {currentBalance}");
41+
}
42+
}
43+
44+
static IEnumerable<(TransactionType type, double amount)> TransactionRecords(string inputText)
45+
{
46+
var reader = new StringReader(inputText);
47+
string? line;
48+
while ((line = reader.ReadLine()) is not null)
49+
{
50+
string[] parts = line.Split(',');
51+
52+
string? transactionType = parts[0]?.Trim();
53+
if (double.TryParse(parts[1].Trim(), out double amount))
54+
{
55+
// Update the balance based on transaction type
56+
if (transactionType?.ToUpper() is "DEPOSIT")
57+
yield return (TransactionType.Deposit, amount);
58+
else if (transactionType?.ToUpper() is "WITHDRAWAL")
59+
yield return (TransactionType.Withdrawal, amount);
60+
}
61+
yield return (TransactionType.Invalid, 0.0);
62+
}
63+
}
64+
}
65+
66+
public enum TransactionType
67+
{
68+
Deposit,
69+
Withdrawal,
70+
Invalid
71+
}
72+
// </IsEnumValue>
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net9.0</TargetFramework>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
<Nullable>enable</Nullable>
8+
</PropertyGroup>
9+
10+
</Project>

0 commit comments

Comments
 (0)