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

Switch expression (modern C#) - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Switch expression (modern C#)
Start with input value
Evaluate switch expression
Match input to pattern/case
Return corresponding result
End with output value
The switch expression takes an input, matches it against patterns, and returns the result of the matched case.
Execution Sample
C Sharp (C#)
string day = "Tuesday";
string type = day switch
{
    "Monday" => "Start of week",
    "Tuesday" => "Second day",
    _ => "Other day"
};
This code uses a switch expression to assign a description based on the day string.
Execution Table
StepInput (day)Switch Case CheckedMatch?Result Assigned
1"Tuesday""Monday"NoNone
2"Tuesday""Tuesday"Yes"Second day"
3N/AStop checkingN/A"Second day"
💡 Match found at step 2, switch expression returns "Second day" and stops.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
day"Tuesday""Tuesday""Tuesday""Tuesday"
typenullnull"Second day""Second day"
Key Moments - 2 Insights
Why does the switch expression stop checking after matching "Tuesday"?
Because switch expressions return the result immediately when a match is found, as shown in execution_table step 2 and 3.
What does the underscore (_) mean in the switch expression?
It means 'any other value' or default case, used if no other case matches, but here it is not reached because "Tuesday" matches earlier.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'type' after step 1?
A"Start of week"
Bnull
C"Second day"
D"Other day"
💡 Hint
Check the 'Result Assigned' column at step 1 in the execution_table.
At which step does the switch expression find a match?
AStep 2
BStep 1
CStep 3
DNo match found
💡 Hint
Look at the 'Match?' column in the execution_table.
If the input day was "Friday", what would the switch expression return?
A"Start of week"
B"Second day"
C"Other day"
Dnull
💡 Hint
Consider the underscore (_) case as the default in the switch expression.
Concept Snapshot
Switch expression syntax:
var result = input switch
{
  pattern1 => value1,
  pattern2 => value2,
  _ => defaultValue
};
It matches input to patterns and returns the matching value immediately.
Full Transcript
This example shows how a modern C# switch expression works. We start with a string variable 'day' set to "Tuesday". The switch expression checks each case in order: first "Monday", then "Tuesday". When it finds "Tuesday", it returns "Second day" immediately and stops checking further cases. The underscore (_) is a catch-all for any other value but is not reached here. The variable 'type' gets assigned the result of the switch expression. This flow helps write clear and concise code for matching values to results.