Switch Statements in C#
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
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:
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
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.