C# - Switch
C# - The Switch Statement and Expression
Section titled “C# - The Switch Statement and Expression”In C#, the switch construct provides a clean way to control program flow based on the value of a variable or expression. It allows you to execute different blocks of code by comparing a value against a list of possible cases. Modern C# offers two forms: the traditional switch statement and the more concise switch expression.
The Traditional switch Statement
Section titled “The Traditional switch Statement”The switch statement is a control-flow statement that executes code associated with a matching case label.
Syntax
Section titled “Syntax”switch (expression){ case constant_value1: // Code to execute break; // Exits the switch
case constant_value2: // Code to execute break;
// You can have any number of case statements
default: // Optional // Code to execute if no other case matches break;}Key Rules
Section titled “Key Rules”- Expression Type: The expression in a
switchstatement can be of an integral type (int,char,byte…), astring, anenum, or, with modern C#, any type thanks to pattern matching. breakis Required: Each non-emptycaseblock must end with a jump statement, most commonlybreak. This prevents accidental “fall-through,” which is a common source of bugs in other languages like C++.- Fall-Through for Empty Cases: You can stack
caselabels to execute the same code for multiple values. The compiler allows fall-through only from an emptycase. defaultCase: The optionaldefaultcase executes if none of the othercaseexpressions match the switch expression. It can be placed anywhere in the switch block, but is conventionally last.
Flow Description
Section titled “Flow Description”- The
switchexpression is evaluated once. - The program control jumps to the
caselabel whose constant value matches the result of the expression. - The code within that
caseblock is executed until abreakstatement is encountered. - If a
breakis hit, control jumps to the first statement after theswitchblock. - If no
caselabel matches, control jumps to thedefaultblock (if one exists).
Example: Grade Evaluation
Section titled “Example: Grade Evaluation”using System;
char grade = 'B';string feedback;
switch (grade){ case 'A': feedback = "Excellent!"; break; case 'B': case 'C': feedback = "Well done."; break; case 'D': feedback = "You passed."; break; case 'F': feedback = "Better try again."; break; default: feedback = "Invalid grade."; break;}
Console.WriteLine($"Feedback for grade {grade}: {feedback}");// Output: Feedback for grade B: Well done.Modern C#: switch Expressions (C# 8.0 and later)
Section titled “Modern C#: switch Expressions (C# 8.0 and later)”The switch expression provides a more concise, functional syntax. Instead of being a statement that controls flow, it’s an expression that returns a value.
Syntax
Section titled “Syntax”var result = variableToSwitchOn switch{ pattern1 => expression1, pattern2 => expression2, _ => defaultExpression // _ is the discard pattern, equivalent to default};Example: Grade Evaluation (Revisited)
Section titled “Example: Grade Evaluation (Revisited)”The previous example can be rewritten far more elegantly:
using System;
char grade = 'B';
string feedback = grade switch{ 'A' => "Excellent!", 'B' or 'C' => "Well done.", // 'or' pattern for multiple values 'D' => "You passed.", 'F' => "Better try again.", _ => "Invalid grade."};
Console.WriteLine($"Feedback for grade {grade}: {feedback}");// Output: Feedback for grade B: Well done.Advanced: Pattern Matching in switch
Section titled “Advanced: Pattern Matching in switch”Modern switch statements and expressions support pattern matching, which lets you switch on an object’s properties, type, or other characteristics, not just constant values.
Example: Shipping Cost Calculator
Section titled “Example: Shipping Cost Calculator”Imagine calculating shipping costs based on the destination and order total. A switch expression with property patterns is perfect for this.
public record Order(decimal Total, string DestinationCountry);
public decimal CalculateShipping(Order order){ return order switch { // Property Pattern: checks properties of the order object { DestinationCountry: "USA" } => 5.00m,
// Property Pattern with a when clause for additional logic { DestinationCountry: "EU", Total: > 100.0m } => 0.00m, // Free shipping for EU orders over 100 { DestinationCountry: "EU" } => 10.00m,
// Discard Pattern: catches all other cases _ => 20.00m // International shipping };}
// Usage:var myOrder = new Order(150.0m, "EU");Console.WriteLine($"Shipping cost: {CalculateShipping(myOrder):C}");// Output: Shipping cost: $0.00Best Practices: When to Use Which
Section titled “Best Practices: When to Use Which”- Use
if-else iffor simple boolean conditions or a small number of checks. - Use a
switchstatement when you need to execute different blocks of statements (multiple lines of code) based on a value and don’t need to return a result directly. - Use a
switchexpression when you need to produce a single value based on a set of conditions. It’s more concise and less error-prone.