switch statements and expressions
Pick one of many cases cleanly with switch, use the modern switch expression, and match ranges with patterns.
else if chain gets hard to read. switch compares one value against a list of cases.
The switch statement
Console.Write("Choose 1-3: ");string? choice = Console.ReadLine(); switch (choice){ case "1": Console.WriteLine("New project"); break; case "2": Console.WriteLine("Open project"); break; case "3": Console.WriteLine("Exit"); break; default: Console.WriteLine("Unknown option"); break;}Choose 1-3: 2 Open project
Each caseends withbreak(orreturn/throw). C# does not let one case “fall through” into the next by accident.defaultruns when no case matches. It is optional, but almost always a good idea.You can switch on int,string,char,enum,booland more.
Several cases, one action
char grade = 'B';switch (grade){ case 'A': case 'B': Console.WriteLine("Great work"); break; case 'C': Console.WriteLine("Good"); break; default: Console.WriteLine("Keep practising"); break;}Great work
The switch expression (C# 8+)
pattern => result, arms are separated by commas, and _ is the “anything else” arm.
int day = 6;string type = day switch{ 6 or 7 => "Weekend", >= 1 and <= 5 => "Weekday", _ => "Invalid"};Console.WriteLine(type);Weekend
>= 1 and <= 5 (relational patterns) and 6 or 7 let one arm match a range or several values.
decimal weightKg = 3.2m;decimal cost = weightKg switch{ <= 1m => 50m, <= 5m => 120m, <= 20m => 300m, _ => 800m};Console.WriteLine($"Shipping: Rs {cost}");Shipping: Rs 120
Show a hint
2 => 28, 4 or 6 or 9 or 11 => 30, >= 1 and <= 12 => 31.
Show the solution
int month = 9;int days = month switch{ 2 => 28, 4 or 6 or 9 or 11 => 30, >= 1 and <= 12 => 31, _ => -1};Console.WriteLine(days);30
Remember
switchcompares one value to many cases;defaultcatches the rest.Every case section ends with break(no accidental fall-through).Switch expressions ( x switch { ... }) return a value and are concise.Patterns: or,and,<,>=and_(anything).