with a break
keyword to jump out of the switch block. The default
keyword defines the block that will be executed if none of the preceding conditions is met.
The following example shows multiple statements in a case
statement:
string symbol = 'MSFT';
switch (symbol) {
case 'MSFT':
break;
case 'GOOG':
break;
case 'YHOO':
break;
default:
Console.WriteLine('Stock symbol not recognized');
break;
}
In C#, fall-throughs are not allowed; that is, each case
block of code must include the break
keyword so that execution can be transferred out of the switch
block (and not 'fall through' the rest of the case
statements). However, there is one exception to this rule — when a case
block is empty. Here's an example:
switch (symbol) {
case 'MSFT':
Console.WriteLine(27.96);
break;
case 'GOOG':
Console.WriteLine(437.55);
break;
case 'YHOO':
Console.WriteLine(27.15);
break;
default:
Console.WriteLine('Stock symbol not recognized');
break;
}
The case
for 'INTC
' has no execution block/statement and hence the execution will fall through into the case for 'YHOO
', which will incorrectly print the output '27.15
'. In this case, you need to insert a break statement after the 'INTC
' case to prevent the fall-through:
switch (symbol) {
case 'MSFT':
Console.WriteLine(27.96);
break;
case 'GOOG':
Console.WriteLine(437.55);
break;
case 'INTC':
case 'YHOO':
Console.WriteLine(27.15);
break;
default:
Console.WriteLine('Stock symbol not recognized');
break;
}
Looping
A loop is a statement, or set of statements, repeated for a specified number of times or until some condition is met. C# supports the following looping constructs:
□ for
□ foreach
□ while
and do-while
for Loop
The for
loop executes a statement (or a block of statements) until a specified expression evaluates to false. The for
loop has the following format:
for (statement; expression; statement(s)) {
//---statement(s)
}
The expression inside the for
loop is evaluated first, before the execution of the loop. Consider the following example:
int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for (int i=0; i<9; i++) {
Console.WriteLine(nums[i].ToString());
}
Here, nums is an integer array with nine members. The initial value of i is 0 and after each iteration it increments by 1. The loop will continue as long as i
is less than 9. The loop prints out the numbers from the array:
1
2
3
4
5
6
7