The syntax of the switch statement is as follows:
Switch(expression)
{
case constant1:
//statements1
break
case constant2:
//statements2
break
case constant3:
//statements3
break
.
.
case constantN:
//statementsN
break
default:
//statement
break:
}
In the preceding syntax,
switch : Refer to the switch keyword that indicates a switch statement
expression: Refer to the expression that is checked in the switch statement. This expression must evaluated to a value of integral, string or Boolean type.
case: Refer to the case keyword that indicates a case statement, which consists of a case label and a labels for corresponding case statements
constants1,constants2,statements3,….statementsN: Refer to the sets of statements corresponding to the case statements. These sets of statements can be a single statement or multiple statements.
break: Refers to the break keyword that indicates a break statement.
default: Refers to the default keyword that indicates the default statement, which has the default label and a set of statements
In switch statements depending on the possible values of the expression there can be as many case statements as you want. The case labels in the case statements have to be distinct and of the same data type as the expression. Unlike the case statements there can be only one default statement. In C# it is statements and default statement in any random order.
The switch statement first evaluates the expression whose value is then checked against the case labels. When a match is found the corresponding case statement is executed. If no match is found the default statement is executed. After this, the statement following the switch statement is executed. If there is no default statement and there is no match with any of the case statements , then the statement following the switch statement is directly executed.
switch case example in console applicatoin as given below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplicationDemo
{
class Program
{
static void Main(string[] args)
{
int enteredNumber;
Console.WriteLine("Enter the number rang of 0 to 5");
enteredNumber = Convert.ToInt32(Console.ReadLine());
switch(enteredNumber)
{
case 0:
Console.WriteLine("you entered ZERO");
break;
case 1:
Console.WriteLine("you entered ONE");
break;
case 2:
Console.WriteLine("you entered TWO");
break;
case 3:
Console.WriteLine("you entered THREE");
break;
case 4:
Console.WriteLine("you entered FOUR");
break;
case 5:
Console.WriteLine("you entered FIVE");
break;
default:
Console.WriteLine("Your number is grater then 5");
break;
}
Console.ReadKey();
}
}
}
Comments