Recall & Review
beginner
What is a switch expression in C#?
A switch expression is a concise way to select a value based on matching patterns. It returns a value directly and uses the syntax with 'switch' and '=>' arrows.
Click to reveal answer
intermediate
How do patterns enhance switch expressions?
Patterns allow matching on types, values, or conditions inside switch expressions, making them more powerful and expressive than simple value matching.
Click to reveal answer
beginner
Example: What does this switch expression do?
object obj = 5;
string result = obj switch {
int i => $"Integer {i}",
string s => $"String {s}",
_ => "Unknown"
};It checks the type of obj. If obj is an int, it returns "Integer 5". If obj is a string, it returns "String" plus the string value. Otherwise, it returns "Unknown".
Click to reveal answer
beginner
What does the underscore (_) mean in switch expressions?
The underscore (_) is a discard pattern that matches anything not matched by previous cases. It acts like a default case.
Click to reveal answer
intermediate
Can switch expressions use relational patterns? Give an example.
Yes, switch expressions can use relational patterns like <, >, <=, >=. Example:
int age = 20;
string category = age switch {
< 13 => "Child",
< 20 => "Teen",
_ => "Adult"
};Click to reveal answer
What keyword starts a switch expression in C#?
✗ Incorrect
Switch expressions start with the 'switch' keyword followed by the expression to match.
In a switch expression, what does the '=>' symbol mean?
✗ Incorrect
The '=>' separates the pattern on the left from the result expression on the right.
What pattern matches any value not matched before in a switch expression?
✗ Incorrect
The underscore (_) is the discard pattern that matches anything else.
Which of these is a valid pattern in a switch expression?
✗ Incorrect
The pattern 'int i' matches any int and assigns it to variable i.
Can switch expressions return values directly?
✗ Incorrect
Switch expressions always return a value directly.
Explain how switch expressions with patterns work in C#.
Think about how you choose an option based on matching conditions.
You got /5 concepts.
Write a simple switch expression that returns "Even" or "Odd" for an integer input.
Use modulo operator (%) inside a pattern or condition.
You got /3 concepts.