0
0
C Sharp (C#)programming~5 mins

Pattern matching in switch in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is pattern matching in a switch statement?
Pattern matching in a switch statement lets you check an expression against different patterns, not just fixed values. It helps you test types, properties, or conditions directly in each case.
Click to reveal answer
beginner
How do you match a type in a switch case using pattern matching?
You write the type name followed by a variable name, like case int number:. This matches if the value is an int and assigns it to number.
Click to reveal answer
intermediate
What does the when keyword do in a switch case?
The when keyword adds an extra condition to a case. The case matches only if the pattern matches and the when condition is true.
Click to reveal answer
intermediate
Explain the difference between case int n: and case int n when n > 0:.
case int n: matches any integer and assigns it to n. case int n when n > 0: matches only positive integers because of the when condition.
Click to reveal answer
beginner
Can you use pattern matching in switch expressions as well as statements?
Yes! Pattern matching works in both switch statements and switch expressions, allowing concise and readable code for selecting values based on patterns.
Click to reveal answer
What does case string s: do in a switch statement?
AMatches any string and assigns it to s
BMatches only empty strings
CMatches any integer and assigns it to s
DMatches null values only
Which keyword adds an extra condition to a switch case pattern?
Aif
Bwhere
Cwhen
Dcase
What happens if no pattern matches in a switch statement with pattern matching?
AThe switch statement is skipped
BThe program crashes
CThe first case runs anyway
DThe default case runs if provided
Which of these is a valid pattern matching case in C#?
Acase n int:
Bcase int n when n < 10:
Ccase (int) n:
Dcase int:
Can pattern matching in switch check properties of an object?
AYes, using property patterns
BOnly with loops
COnly with if statements
DNo, only types
Describe how pattern matching improves switch statements in C#.
Think about how you can check more than just fixed values.
You got /4 concepts.
    Explain how to use the 'when' keyword in a switch case with an example.
    It adds extra conditions to cases.
    You got /4 concepts.