-
C# Switch
-
The switch keyword offers a simple, readable, and developer-friendly way to evaluate a single value against several possible outcomes.
When you start building real-world applications in C#, one of the most important skills you’ll develop is writing clean and structured decision-making logic. Many beginners rely heavily on if-else statements, but as the number of conditions grows, if-else blocks become harder to read and maintainThis is where the switch statement shines.
What Is a switch Statement in C#?
In C#, the
switchstatement provides a clean and efficient way to evaluate a single expression against several possible values. Based on the matched case, it runs the corresponding block of code, making complex conditional logic easier to read and maintain.Syntax of switch in C#
How it works:switch (expression) { case value1: // Statements for case 1 break; case value2: // Statements for case 2 break; default: // Statements when no case matches break; }- C# checks the
switchvalue once. - It compares that value with each
case. - When it finds a match, that code runs.
breakstops further execution.- If none match,
defaultexecutes.
Example1 - Selecting a month name:
int month = 10; switch (month) { case 1: Console.WriteLine("January"); break; case 2: Console.WriteLine("February"); break; case 10: Console.WriteLine("October"); break; default: Console.WriteLine("Invalid month"); break; }The variable
monthcontains 10, so the switch finds the matching case and prints October.
Example 2: Handling User Commands With Strings
Strings are frequently used in applications — menus, commands, statuses, etc.
Note: C# fully supports switching on strings.
This is extremely helpful when creating console menus, UI navigation, and command-based programs.string action = "login"; switch (action) { case "login": Console.WriteLine("User logged in."); break; case "logout": Console.WriteLine("User logged out."); break; case "signup": Console.WriteLine("Creating new account..."); break; default: Console.WriteLine("Unknown action"); break; }
Example 3: Grouping Multiple Cases
Sometimes multiple values should produce the same output.
Instead of repeating code, you can stack cases together.
This improves both performance and readabilitychar letter = 'a'; switch (letter) { case 'a': case 'e': case 'i': case 'o': case 'u': Console.WriteLine("Vowel"); break; default: Console.WriteLine("Consonant"); break; }
Conclusion
The switch statement in C# is an essential control structure that helps keep your decision-making logic clean, structured, and easy to understand. Whether you are handling numbers, user choices, or status codes, switch provides a neat solution compared to long if-else chains.
With the addition of switch expressions in modern C#, developers now have an even more elegant and compact way to write value-based logic.
- C# checks the