Concept Flow - Why pattern matching matters
Input value
Match pattern 1?
No→Match pattern 2?
Execute action 1
Done
The program checks the input against patterns one by one and runs the matching action, making code clearer and safer.
object obj = 42; switch (obj) { case int i: Console.WriteLine($"Integer {i}"); break; default: Console.WriteLine("Unknown type"); break; }
| Step | Input Value | Pattern Checked | Match Result | Action Taken | Output |
|---|---|---|---|---|---|
| 1 | 42 (int) | case int i | Yes | Print Integer 42 | Integer 42 |
| 2 | 42 (int) | default | No | No action |
| Variable | Start | After Step 1 | After Step 2 | Final |
|---|---|---|---|---|
| obj | 42 (int) | 42 (int) | 42 (int) | 42 (int) |
| i | undefined | 42 | undefined | 42 |
Pattern matching checks a value against patterns in order. When a pattern matches, its code runs and the check stops. It combines type check and variable extraction. Default case handles unmatched values. This makes code clearer and safer than many if-else checks.
is in C#?is Type variable inside the if condition, like obj is int number.object obj = 42;
switch (obj)
{
case int i:
Console.WriteLine($"Integer: {i}");
break;
case string s:
Console.WriteLine($"String: {s}");
break;
default:
Console.WriteLine("Unknown type");
break;
}case int i because obj is an int, so it prints "Integer: 42".object obj = "hello";
if (obj is int number)
{
Console.WriteLine(number);
}obj is int number is false, so the block never runs.List<object> items = new() { 1, -2, "two", 3.0, null };, which pattern matching expression correctly counts only the positive integer values?Pass the test and this pattern moves unknown