|
The switch statement is very similar to the if statement. The switch statement does not take conditions such as the > or = operators. It takes variables and compares it to the case blocks.
switch(''variable'')
{
case 'a':
''execute code''
break;
case 'b':
''execute code''
break;
case 'c':
''execute code''
break;
default:
''This code will execute if all other comparisons don't match''
break;
}
How the switch statement works: A variable or literal in the switch parenthesis is compared with each case. When it finds a match it breaks out of the switch block and proceeds with the program.
switch(variable) -- The variable holds a certain value either it be a number, string or character value. The program then examines the first case and it determines if the value of variable is equal to a. If variable is equal to a it will execute the code below it. After the code has been executed the break command will execute. Once the break command is executed the switch structure is exited. In the case where the first case evaluates to false it goes to the second case statement.
default: -- When the test varaible does not match any of the case comparisons the default case is executed. The default case should always be at the bottom to ensure it is the last to be evaluated.
Example code:
using System;
class Program
{
static void Main(string[] args)
{
char grade = 'b';
switch (grade)
{
case 'a':
Console.WriteLine("Outstanding student");
break;
case 'b':
Console.WriteLine("Good student");
break;
case 'c':
Console.WriteLine("Average student");
break;
case 'd':
Console.WriteLine("Need a little practice");
break;
default:
Console.WriteLine("Need alot of practice");
break;
}
Console.Read();
}
}
Output
Good student
As you can see the variable grade equals b. if first compares the first first which obviously turns out to be false. Then it proceeds to the second case statement. The comparison matches the variabe so the code is executed and the switch statements is exited.
- Default will execute if all other comparisons dont match.
- break exits the switch block. Without a break statement will produce an error.
- return, break and goto statements can exit switch blocks. More on this later
|