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

Switch expression (modern C#) - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Switch Expression Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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));
AMonday
BOther
CTuesday
DWednesday
Attempts:
2 left
💡 Hint
Look at the input value and match it with the switch cases.
Predict Output
intermediate
2: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)));
ASenior
BAdult
CChild
DUnknown
Attempts:
2 left
💡 Hint
Check the age property and the conditions in the switch.
Predict Output
advanced
2: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));
AY-axis
BX-axis
COrigin
DPlane
Attempts:
2 left
💡 Hint
Look at the tuple values and which pattern matches first.
Predict Output
advanced
2: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));
A4
B3
C2
D1
Attempts:
2 left
💡 Hint
Check which condition the score 85 satisfies first.
🧠 Conceptual
expert
2: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)?
A"Has value"
BThrows NullReferenceException
C"Empty string"
D"No input"
Attempts:
2 left
💡 Hint
Check how null is matched in the switch expression.