How to Use Switch Case in C# - Simple Guide
In C#, use the
switch statement to select one of many code blocks to execute based on a variable's value. Each case defines a value to match, and break ends the case. The default case runs if no other case matches.Syntax
The switch statement evaluates a variable and compares it to multiple case values. When a match is found, the code inside that case runs until a break is reached, which exits the switch. The default case runs if no other case matches.
- switch(expression): The variable or expression to check.
- case value: A possible value to match.
- break; Ends the current case.
- default: Runs if no case matches.
csharp
switch (variable) { case value1: // code to run if variable == value1 break; case value2: // code to run if variable == value2 break; default: // code to run if no case matches break; }
Example
This example shows how to use switch to print a message based on a day number.
csharp
using System; class Program { static void Main() { int day = 3; switch (day) { case 1: Console.WriteLine("Monday"); break; case 2: Console.WriteLine("Tuesday"); break; case 3: Console.WriteLine("Wednesday"); break; case 4: Console.WriteLine("Thursday"); break; case 5: Console.WriteLine("Friday"); break; default: Console.WriteLine("Weekend"); break; } } }
Output
Wednesday
Common Pitfalls
Common mistakes when using switch include forgetting break; which causes "fall-through" to the next case, and not including a default case which can leave some values unhandled. Also, switch only works with certain types like integers, strings, and enums.
csharp
/* Wrong: Missing break causes fall-through */ switch (value) { case 1: Console.WriteLine("One"); // missing break here causes fall-through case 2: Console.WriteLine("Two"); break; } /* Correct: Each case ends with break */ switch (value) { case 1: Console.WriteLine("One"); break; case 2: Console.WriteLine("Two"); break; }
Quick Reference
- Use
switchto replace multipleif-elsewhen checking one variable. - Always end cases with
break;to avoid running unwanted code. - Include a
defaultcase to handle unexpected values. switchsupports types likeint,string, andenum.
Key Takeaways
Use
switch to select code based on a variable's value cleanly.Always include
break; to prevent fall-through between cases.Add a
default case to handle unexpected values.switch works well with integers, strings, and enums.Avoid complex logic inside cases; keep them simple and clear.