In C#, the switch case statement checks one variable for various possible values (cases) and executes the case which is true. Switch case statements are mainly used in menu driven programs where various choices are thrown to user out of which 1 is to be chosen.
Syntax
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
switch(<variable>) { case <value1> : //statements break; case<value 2>: //statements break; case<value 3>: //statements break; default: //if all cases don’t match then this default will be executed break; } |
C# switch case Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
using System; public class SwitchCaseExample1 { public static void Main (string[] args) { Console.WriteLine("Enter a Number"); int a=Convert.ToInt32(Console.ReadLine()); switch(a) { case 10: Console.WriteLine("It is 10"); break; case 20: Console.WriteLine("It is 20"); break; case 30: Console.WriteLine("It is 30"); break; case 40: Console.WriteLine("It is 40"); break; default: Console.WriteLine("It's not from the set of values given as (10,20,30,40)"); break; } } } |
Output
1 2 3 4 5 6 |
20 It is 20 80 It’s not from the set of values given as (10,20,30,40) |
Note:
- We can’t use two parameters in switch statement.
- The case value must be an integer.