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

Switch expressions with patterns in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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#?
Aswitch
Bcase
Cmatch
Dselect
In a switch expression, what does the '=>' symbol mean?
AIt declares a variable
BIt means 'or'
CIt ends the switch
DIt separates the pattern from the result expression
What pattern matches any value not matched before in a switch expression?
Adefault
Bnull
C_
Delse
Which of these is a valid pattern in a switch expression?
Aint = 5
Bint i
Cint => 5
Dint ?
Can switch expressions return values directly?
AYes
BNo
COnly in C# 7
DOnly with enums
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.