C# Switch: Select Cases and Return Clear Results
Use switch to map one input to a clear set of alternatives. Learn the difference between selecting statements and returning a value, share documented aliases, and handle unexpected choices deliberately.
What you will understand
- Trace a switch statement from its input to the selected section.
- Distinguish break from return and avoid accidental fall-through.
- Share one body between several documented case labels.
- Write a switch expression with result arms and a deliberate catch-all policy.
- Handle missing, differently cased and unsupported command text.
- Understand first-match guards, relational patterns and unreachable arms.
- Distinguish exhaustive coverage from a correct domain response.
- Build an export-request selector with useful rejection feedback.
Use switch when one input chooses among named cases
A switch selects behavior by matching one input against cases. A menu choice, a command token or a format code is often easier to read as a set of named cases than as a long sequence of repeated equality checks. Start with the possible inputs and the required response for each one.
The statement form writes switch (input), then a braced set of sections. A case label identifies a matching value and ends with a colon. The statements in the selected section run. A break then exits the switch, allowing later statements in the surrounding program to continue.
You need the strings, Boolean rules and if/else lessons first. Each editor below is a complete separate Program.cs. Two examples deliberately fail compilation, and one deliberately fails at runtime. Predict a normal input and an unknown input before selecting Run.
Show saved practice.
Menu check finished.
switch evaluates choice and selects a matching section. case 2 matches this value, its statements run, and break exits the switch. The message after the switch still runs. These are printed menu actions, not calls that load courses or saved records.
Program.cs · Give an unknown choice useful feedback
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Choose 1 or 2.
default handles an input that matches no case. It does not change choice to a valid value or automatically ask again. Test an unexpected choice deliberately instead of assuming the surrounding interface will always supply a known option.
Sections need an exit; aliases can share a body
C# does not allow ordinary execution to run from the end of a completed section into the next section. Use break to leave the switch, or another appropriate control transfer such as return. A return ends the current method or this top-level run; it does more than break.
Several labels can appear before one shared body. That is useful for documented aliases such as md and markdown. The shared labels do not mean both sections execute, and no completed body is falling through into another one.
A switch statement can omit default. If no section matches, execution simply continues after the statement. That may be intentional, but a user-facing choice often benefits from explicit unknown-input feedback. default supplies a fallback; it does not turn an invalid input into a valid choice by itself.
Markdown export selected.
Both labels lead to the same section. This is a shared body, not execution falling through a completed section. String constant cases match exact case-sensitive text: MARKDOWN would reach default unless you deliberately normalize or otherwise match it.
Program.cs · A completed section cannot fall into the next one
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Compilation fails: control cannot fall through from one completed case section.C# does not permit this ordinary fall-through after executing statements. End the first section with break when the switch should continue afterward, or another appropriate control transfer. Do not assume JavaScript or C-style fall-through rules apply.
Program.cs · Return ends the run, not only the switch
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Goodbye.
return exits this top-level program, so the final message is not reached. break in the same location would instead exit only the switch and allow the final message. Choose the transfer that expresses the intended flow; a switch section does not always need break specifically.
Program.cs · An unmatched statement can do nothing
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
After switch.
A switch statement without a matching case and without default simply continues after the statement. That is legal, but can silently omit useful feedback. Contrast this with a nonexhaustive switch expression later: an expression must produce a result or fail.
Use a switch expression when selection returns one value
A switch expression puts the input before the switch keyword. Each arm has a pattern, an arrow and one result expression. Commas separate arms, and the completed assignment ends with a semicolon. Do not mix this syntax with case labels, colons and break statements from the statement form.
The selected arm supplies the value that is assigned or used by the surrounding expression. Use this form for a small mapping, such as a known format token to its extension, when all results fit the intended target type. Several actions or an early rejection path may read more naturally as a statement.
The discard pattern _ is a catch-all arm. It matches any remaining input and usually belongs last. A useful fallback must reflect the domain: a string saying unsupported may be suitable for a demonstration, while an actual request flow should avoid producing a misleading successful result.
Program.cs · Map a choice to one returned value
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Extension: .md
The input appears before switch. Each arm has a pattern, => and a result expression; commas separate arms. The discard pattern _ is a catch-all result. The assignment ends with a semicolon. There are no case labels, colons or break statements inside this expression.
Program.cs · A missing expression result fails at runtime
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Selecting extension
Then execution fails with SwitchExpressionException.This expression has no arm for pdf. In the .NET runtime used by these editors it throws SwitchExpressionException. The compiler normally warns about missing coverage, but a warning does not necessarily prevent execution. Add a deliberate catch-all policy rather than treating an unknown format as a known one.
Decide how text should match before selecting a case
String constant cases use exact case-sensitive matching. A space-padded or differently cased command will not match its plain lowercase token automatically. Do not rely on a human reader seeing the spellings as equivalent; define the token policy explicitly.
The normalization example first rejects a missing or blank answer, then trims the text and converts the fictional ASCII format tokens to invariant lowercase. This is an application convention for a small documented vocabulary. Keep general display names and other identity fields separate from that convention.
The or pattern lets one expression arm match more than one alias. It is pattern syntax, not the Boolean operator || joining two comparisons. In a statement, adjacent case labels are another readable way to share a body. Neither alias support nor normalization establishes that every other token should be accepted.
Program.cs · Clean a command before matching its token
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Extension: .md
The guard handles absence and blank text first. The fictional ASCII format-token policy trims and uses invariant lowercase spelling before matching. The or pattern shares one result between aliases. This convention is not a rule for rewriting display names or every possible identifier.
Match order and guards determine the selected section
A when guard adds a Boolean requirement after a matching pattern. The pattern and guard must both succeed for that section to be chosen. If the pattern matches but its guard is false, selection can continue to a later applicable section.
Place a guarded specific section before an unguarded fallback for the same label. Otherwise the earlier fallback already covers its inputs. A switch expression also rejects a specific arm placed below a catch-all, because that later arm cannot be selected.
Although default in a statement is a fallback regardless of where its label is written, put it last for clarity. Do not transfer that special statement rule to the expression discard arm: _ is an ordinary catch-all pattern considered in arm order.
Program.cs · A matching label can have an additional condition
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Express is unavailable; choose standard.
when adds a Boolean condition to that case. The express label matches, but the first guard is false, so selection continues to the next matching section. Put the guarded specific case before the unguarded fallback for the same label; otherwise it can never be selected.
Program.cs · A catch-all arm belongs after specific arms
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Compilation fails: the md arm is unreachable after the catch-all.The discard matches every input before the specific arm can be reached. The compiler rejects this arm ordering. In a switch expression, place _ last. This differs from the statement label default, which is a fallback regardless of its physical position.
Choose the structure that makes numeric categories easiest to verify
Modern switch patterns can express relational ranges and combine alternatives with or. For a score band, reject out-of-domain values before classifying the valid ones. A score of 101 should not accidentally reach a high-score arm merely because it exceeds ninety.
Within a switch expression, the first matching arm supplies the result. Reaching a lower threshold can carry the knowledge that an earlier higher threshold failed. Test the exact boundaries and their neighbors, just as you did with else-if chains.
You do not need to replace a clear if/else chain with switch patterns. Prefer if when the rule combines unrelated conditions or when the sequence is clearer as guards. Prefer switch when the input-centered set of alternatives makes the intended mapping easier to inspect.
Program.cs · Use relational patterns only when the categories stay clear
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
On track
The invalid-input arm runs before the valid bands, so 101 does not become Excellent. Remaining arms are considered in source order, with the first match supplying the result. These are relational patterns, not standalone expressions such as score >= 90 inside the arm. A familiar if/else chain is also a good choice for ranges.
Exhaustive syntax is not the same as a correct fallback policy
A statement can continue silently after no match, but a switch expression needs a result. On the .NET runtime used by these editors, an unmatched nonexhaustive expression throws SwitchExpressionException. The compiler often warns about missing coverage, yet a warning may not prevent the program from running.
A catch-all avoids an unmatched expression but can still encode the wrong rule. Mapping every unexpected delivery token to the standard fee hides invalid input and produces a misleading quote. The guided repair rejects the unknown token before the fee output instead.
For each selector, test every documented case, every alias, blank or missing text when applicable, and at least one unsupported value. State what success actually does. The export-request lab chooses and prints a filename; it does not create a file or complete a download.
Guided repair: reject an unsupported option
An unknown overnight option silently receives the standard-delivery fee. Reject unsupported tokens before output, while still quoting the two supported choices. Use the structure that makes the rejection path clear.
Program.cs · Do not disguise an unknown option as a known one
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Delivery fee: 4.00
The fallback silently quotes standard delivery for an unsupported token. The expression is exhaustive but its policy is wrong. Exhaustiveness means every input gets handled; it does not prove each input is handled correctly.
Repair checkpoints
- standard must quote 4.00 and express must quote 9.00.
- overnight and an empty present token must print the supported-choice message.
- The rejected path must not print a delivery fee.
- Every continuing accepted path must assign fee.
- Do not treat exhaustive matching as proof that the fallback policy is correct.
Reveal the repair and explanation
Program.cs · Reject an unknown option before printing a fee
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Choose standard or express.
Every continuing path assigns fee. The unknown path prints useful feedback and returns, so no misleading quote appears. A statement is convenient here because selection includes an early exit. You could design an expression returning a richer result later, when the course covers those types.
Independent lab: an export request selector
Choose an export filename from a required format token. Support md/markdown and txt/text aliases after the stated trimming and casing policy. Missing and unsupported choices must produce feedback without a successful filename.
Acceptance checklist
- Keep rawFormat = " Markdown " and fileStem = "lesson-notes" for the reference run.
- Reject null, empty and whitespace-only input before calling string instance methods.
- Trim and use invariant lowercase for this fixed ASCII token vocabulary.
- Use shared case labels for md/markdown and txt/text.
- Return after unknown-input feedback so no filename is printed.
- Print Export file: lesson-notes.md for the reference input.
- Explain that the filename is a display result; no file is created and the fixed stem is not a general filename-validation implementation.
Program.cs · Export request starter
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Export file: lesson-notes.txt
The starter neither cleans the token nor recognizes the documented alias, and unknown or missing choices silently become plain text. The lab requires explicit rejection and a clear distinction between format selection and actually writing a file.
Show hints
- Bring the required-string guard forward from the input lesson.
- Choose statement sections when early rejection is easier to express than a value-returning arm.
- Check aliases against the cleaned token, not the original padded input.
Reveal the reference solution
Program.cs · Export request reference solution
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Export file: lesson-notes.md
The required-input guard runs before normalization, shared labels handle aliases, and the default section rejects unsupported tokens. Only a recognized format reaches the filename output. fileStem is a fixed exercise string; this program does not validate filesystem names or create an export file.
Changed-input checks
- md, markdown, MD and surrounding-space Markdown select .md.
- txt and TEXT select .txt.
- pdf reports the supported formats and prints no export filename.
- null, an empty string and whitespace-only text report a required-format message.
- Changing the fixed stem to practice changes only the printed filename.
Recap: match the syntax to the selection
Use a statement for selected statements and an expression for one returned value. Check known cases, aliases and the fallback separately.
switch (input)- Select a section of statements by matching one input.
case value:- Introduce a matching section; adjacent labels can share a body.
break / return- Exit the switch versus exit the current method or top-level run.
default:- Handle an unmatched statement input with a deliberate fallback.
input switch { pattern => result }- Return the selected arm’s value in an expression.
_ => result- Catch remaining expression inputs; put this arm last.
pattern when condition- Require both the pattern match and a Boolean guard.
"md" or "markdown"- Match either alias within one pattern arm.
Frequently asked questions
Do all cases need break?
A completed section needs an appropriate control transfer. break exits the switch, while return exits the enclosing method or top-level program. Adjacent labels may share one body without a break between labels.
What happens without default?
An unmatched switch statement simply continues afterward. A switch expression without a matching arm instead fails at runtime on the .NET runtime used here.
Are string cases case-insensitive?
No. String constant cases match case-sensitive text. Apply an explicit documented token policy or another appropriate matching approach when case should not matter.
Is _ the same as default?
They play similar fallback roles in different syntax. default is the statement label; _ is a discard pattern used as an expression catch-all. Pattern arm order matters, so put _ last.
When should I use a switch expression?
When the selection naturally returns one value. A statement can be clearer for several actions or rejection paths that end execution early.
Does a catch-all make every input valid?
No. It ensures the input is handled. The fallback can reject an invalid choice; silently replacing it with a valid option may be the wrong policy.
Can you explain the selected case?
Distinguish sections, arms, control transfers and unknown-input policies. Read each explanation after checking your answers.
Next step and references
A switch organizes alternatives around one input. Keep statement and expression syntax distinct, share documented aliases clearly, and choose an honest fallback. Coverage and domain validity are separate questions.
Next is C# While and Do-While Loops. You will repeat work with a condition, trace the state changes and make sure a loop has a clear way to stop.
Official references
Original SovranCode explanations, examples and exercises. Technical details were checked against these references.
Last updated: .