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.