How to use switch statement in c# ?

Switch statement is used to check a variable with a set of conditions called cases. We can check a variable whether the value satisfies certain conditions.
For example below I have checked a variable is A, B or C. in some case we need to do some operations according to the check then we can go for the switch case.

Syntax for switch statement in c#

switch(expression_data) {
case condition1 :
Method1(s);
break; /* optional */
case condition2 :
Method2(s);
break; /* optional */
.
.
.
.
.

default : /* Default is optional */
methodN(s);
}

Example for switch statement in c#

using System;
namespace FindVariable
{
class Program
{
static void Main(string[] args)
{
char character_variable = 'B';

switch (character_variable)
{
case 'A':
Console.WriteLine("Variable has value A");
break;
case 'B':
Console.WriteLine("Variable has value B");
break;
case 'C':
Console.WriteLine("Variable has value C");
break;

default:
Console.WriteLine("The variable not have the chartectors A,B and C");
break;
}
Console.WriteLine("The variable has value{0}", character_variable);
Console.ReadLine();
}
}
}

Output

Variable has value B
The variable has value B

Leave a Reply