C# Switch Statement

C# Switch Statement

The switch statement in C# is used to execute one block of code from many choices. It is a clean alternative to long if...else if chains when comparing a single value.


 Basic switch Syntax


 


 How switch Works

  • The expression is evaluated once

  • Value is compared with each case

  • break exits the switch block

  • default runs if no case matches


 Switch with string


 


 Multiple Cases with Same Code


 


 Switch Without break (Fall-through)

❌ Not allowed in C# unless cases are empty.



 Switch with enum


 


 Modern C# Switch Expression (Advanced)


 


 When to Use switch

✔ Many fixed values
✔ Cleaner than if-else
✔ Works with int, char, string, enum


 Summary

switch selects one case
break prevents fall-through
default handles unmatched cases
✔ Switch expressions are concise

You may also like...