If you would like to perform a series of specific checks, switch...case
is present in C# only for this. The general structure of the switch...case
statement is:
switch(integral or string expression)
{
case constant-expression:
// statements
breaking or jump statement
// another case blocks
...
default:
statements
breaking or jump statement
}
There are some details to recollect when using the switch...case
statement in C#:
{}
brackets to mark the block in the switch...case as we usually neutralize C#The switch statement may be a clear group of statements to implementing selection among many options (namely, a choice among a couple of other ways for executing the code). It requires a selector, which is calculated to a particular value. The selector type might be an integer number, char, string, or enum. If we would like to use for example an array or a float as a selector, it'll not work. For non-integer data types, we should always use a series of if statements.
int number = 6;
switch (number)
{
case 1:
Console.WriteLine("this is case 1");
break;
case 2:
Console.WriteLine("this is case 2");
break;
case 3:
Console.WriteLine("this is case 3");
break;
case 4:
Console.WriteLine("this is case 4");
break;
case 5:
Console.WriteLine("this is case 5");
break;
case 6:
Console.WriteLine("this is case 6");
break;
case 7:
Console.WriteLine("this is case 7");
break;
case 8:
Console.WriteLine("this is case 8");
break;
case 9:
Console.WriteLine("this is case 9");
break;
case 10:
Console.WriteLine("this is case 10");
break;
default:
Console.WriteLine("Unknown number!");
break;
}
this is case 6
In the above example, we are implementing multiple statements by using case statements with the break. First of all integer value of the selector will be calculated that is 6. Then it will be compared with all case statement integer numbers and then print the related output if no match is found then the default statement will be called.
A switch statement under the switch statement is known as a nested switch statement
int number = 2;
switch (number)
{
case 1:
Console.WriteLine(11);
break;
case 2:
switch(number + 1)
{
case 3:
Console.WriteLine(number + 1);
break;
}
switch(number + 2)
{
case 4:
Console.WriteLine(number + 2);
break;
}
break;
default:
Console.WriteLine(100);
break;
}
3
4