Challenge - 5 Problems
Switch Expression Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a simple switch expression
What is the output of this C# code using a switch expression?
C Sharp (C#)
string GetDayType(int day) => day switch { 1 => "Monday", 2 => "Tuesday", 3 => "Wednesday", _ => "Other" }; Console.WriteLine(GetDayType(2));
Attempts:
2 left
💡 Hint
Look at the input value and match it with the switch cases.
✗ Incorrect
The input is 2, which matches the case '2' returning "Tuesday".
❓ Predict Output
intermediate2:00remaining
Switch expression with property pattern
What will this code print?
C Sharp (C#)
record Person(string Name, int Age); string Describe(Person p) => p switch { { Age: < 18 } => "Child", { Age: >= 18 and < 65 } => "Adult", { Age: >= 65 } => "Senior", _ => "Unknown" }; Console.WriteLine(Describe(new Person("Alice", 70)));
Attempts:
2 left
💡 Hint
Check the age property and the conditions in the switch.
✗ Incorrect
Age 70 matches the pattern { Age: >= 65 }, so it returns "Senior".
❓ Predict Output
advanced2:00remaining
Switch expression with tuple patterns
What is the output of this code?
C Sharp (C#)
string GetResult(int x, int y) => (x, y) switch { (0, 0) => "Origin", (_, 0) => "X-axis", (0, _) => "Y-axis", _ => "Plane" }; Console.WriteLine(GetResult(0, 5));
Attempts:
2 left
💡 Hint
Look at the tuple values and which pattern matches first.
✗ Incorrect
The tuple (0,5) matches the pattern (0, _) which returns "Y-axis".
❓ Predict Output
advanced2:00remaining
Switch expression with when clause
What will this code print?
C Sharp (C#)
int Grade(int score) => score switch { var s when s >= 90 => 4, var s when s >= 80 => 3, var s when s >= 70 => 2, var s when s >= 60 => 1, _ => 0 }; Console.WriteLine(Grade(85));
Attempts:
2 left
💡 Hint
Check which condition the score 85 satisfies first.
✗ Incorrect
85 is >= 80 but less than 90, so it returns 3.
🧠 Conceptual
expert2:00remaining
Behavior of switch expression with null input
Consider this switch expression:
string DescribeInput(string? input) => input switch
{
null => "No input",
"" => "Empty string",
_ => "Has value"
};
What is the output of DescribeInput(null)?
Attempts:
2 left
💡 Hint
Check how null is matched in the switch expression.
✗ Incorrect
The input is null, so it matches the first case returning "No input".