Bird
Raised Fist0
C Sharp (C#)programming~10 mins

Why pattern matching matters in C Sharp (C#) - Visual Breakdown

Choose your learning style10 modes available
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.
Execution Sample
C Sharp (C#)
object obj = 42;
switch (obj)
{
  case int i:
    Console.WriteLine($"Integer {i}");
    break;
  default:
    Console.WriteLine("Unknown type");
    break;
}
This code checks if obj is an int and prints it; otherwise, it prints 'Unknown type'.
Execution Table
StepInput ValuePattern CheckedMatch ResultAction TakenOutput
142 (int)case int iYesPrint Integer 42Integer 42
242 (int)defaultNoNo action
💡 Pattern matched at step 1, so switch ends after executing that case.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
obj42 (int)42 (int)42 (int)42 (int)
iundefined42undefined42
Key Moments - 3 Insights
Why does the switch stop after the first matching pattern?
Because once a pattern matches (see execution_table step 1), the corresponding action runs and the switch exits to avoid running other cases.
What if the input doesn't match any pattern?
The default case runs (execution_table step 2 shows no match for int, so default would execute), ensuring the program handles unexpected inputs safely.
Why use pattern matching instead of if-else?
Pattern matching makes code clearer and safer by combining type checks and variable extraction in one step, as shown by the concise match and action in the sample.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'i' after step 1?
A42
Bundefined
Cnull
D0
💡 Hint
Check variable_tracker row for 'i' after step 1.
At which step does the pattern match successfully?
AStep 2
BNo match
CStep 1
DBoth steps
💡 Hint
See execution_table 'Match Result' column.
If obj was a string instead of int, which action would run?
APrint Integer value
BDefault case action
CNo action
DError thrown
💡 Hint
Default case runs when no pattern matches, see execution_table step 2.
Concept Snapshot
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.
Full Transcript
Pattern matching in C# lets you check a value against different patterns and run code for the first match. The flow starts with an input value, then checks each pattern in order. If a pattern matches, the program runs the related action and stops checking further. If no pattern matches, the default case runs. This approach is clearer and safer than many if-else statements because it combines type checking and variable extraction in one step. For example, if the input is an integer 42, the pattern 'case int i' matches, assigns 42 to i, and prints it. If the input was not an int, the default case would print 'Unknown type'. This helps avoid errors and makes code easier to read and maintain.

Practice

(1/5)
1. What is the main benefit of using pattern matching in C#?
easy
A. It simplifies checking types and extracting data in one step.
B. It makes the program run faster by optimizing CPU usage.
C. It automatically fixes syntax errors in the code.
D. It replaces all loops with recursive calls.

Solution

  1. Step 1: Understand pattern matching purpose

    Pattern matching lets you check a variable's type and extract its data in a single, clear step.
  2. Step 2: Compare with other options

    Options A, B, and D describe unrelated or incorrect benefits not provided by pattern matching.
  3. Final Answer:

    It simplifies checking types and extracting data in one step. -> Option A
  4. Quick Check:

    Pattern matching = Simplifies type checks [OK]
Hint: Pattern matching combines type check and data use in one step [OK]
Common Mistakes:
  • Thinking pattern matching speeds up CPU performance
  • Confusing pattern matching with syntax error fixing
  • Believing pattern matching replaces loops
2. Which of the following is the correct syntax for pattern matching with is in C#?
easy
A. if (obj is int number) { /* use number */ }
B. if (obj is int) number { /* use number */ }
C. if (obj is int: number) { /* use number */ }
D. if (obj int is number) { /* use number */ }

Solution

  1. Step 1: Recall correct pattern matching syntax

    The correct syntax uses is Type variable inside the if condition, like obj is int number.
  2. Step 2: Identify syntax errors in other options

    Options A, B, and C have incorrect order or punctuation that cause syntax errors.
  3. Final Answer:

    if (obj is int number) { /* use number */ } -> Option A
  4. Quick Check:

    Correct pattern matching syntax = if (obj is int number) { /* use number */ } [OK]
Hint: Remember: 'is Type variable' is the pattern matching syntax [OK]
Common Mistakes:
  • Placing variable before type in 'is' expression
  • Using colon ':' instead of space
  • Mixing order of keywords
3. What will be the output of this code?
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;
}
medium
A. String: 42
B. Integer: 42
C. Unknown type
D. Compilation error

Solution

  1. Step 1: Identify the type of obj

    obj is assigned the integer value 42, so its runtime type is int.
  2. Step 2: Match switch cases

    The switch matches case int i because obj is an int, so it prints "Integer: 42".
  3. Final Answer:

    Integer: 42 -> Option B
  4. Quick Check:

    obj is int 42, so output = "Integer: 42" [OK]
Hint: Match the runtime type to the correct case in switch [OK]
Common Mistakes:
  • Assuming obj is string because of quotes missing
  • Thinking default case runs first
  • Confusing compile-time and runtime types
4. Identify the error in this pattern matching code:
object obj = "hello";
if (obj is int number)
{
    Console.WriteLine(number);
}
medium
A. The variable 'number' is not declared before use.
B. The 'is' keyword cannot be used with variables.
C. Missing braces around the if block.
D. The pattern matching condition will never be true for a string.

Solution

  1. Step 1: Analyze the type of obj

    obj holds a string "hello", but the pattern checks if obj is an int.
  2. Step 2: Understand pattern matching behavior

    Since obj is a string, the condition obj is int number is false, so the block never runs.
  3. Final Answer:

    The pattern matching condition will never be true for a string. -> Option D
  4. Quick Check:

    obj is string, pattern checks int, so condition false [OK]
Hint: Check if variable type matches pattern type before using it [OK]
Common Mistakes:
  • Assuming variable 'number' must be declared separately
  • Thinking 'is' cannot be used with variables
  • Ignoring that condition can be false without error
5. Given a list of objects List<object> items = new() { 1, -2, "two", 3.0, null };, which pattern matching expression correctly counts only the positive integer values?
hard
A. items.Count(item => item is string s)
B. items.Count(item => item is int)
C. items.Count(item => item is int number && number > 0)
D. items.Count(item => item != null)

Solution

  1. Step 1: Understand the goal

    We want to count only positive integers in the list, ignoring other types and null.
  2. Step 2: Analyze each option

    items.Count(item => item is int) counts all ints but does not filter by value; items.Count(item => item is int number && number > 0) counts ints greater than 0, which matches positive integers; items.Count(item => item is string s) counts strings; items.Count(item => item != null) counts all non-null items.
  3. Step 3: Choose the best option

    items.Count(item => item is int number && number > 0) uses pattern matching with a condition to count only positive integers, which is a precise use of pattern matching.
  4. Final Answer:

    items.Count(item => item is int number && number > 0) -> Option C
  5. Quick Check:

    Pattern matching with condition filters integers correctly [OK]
Hint: Use 'is Type var && condition' to filter precisely [OK]
Common Mistakes:
  • Counting all ints without condition when needed
  • Counting strings or non-null items by mistake
  • Not using variable in pattern matching for conditions
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard