25.12.2015 Views

Professional

1l6xhbR

1l6xhbR

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Understanding switch statement syntax<br />

The syntax of a switch statement is as follows (switch, case, and default are keywords):<br />

switch ( controllingExpression )<br />

{<br />

case constantExpression :<br />

statements<br />

break;<br />

case constantExpression :<br />

statements<br />

break;<br />

...<br />

default :<br />

statements<br />

break;<br />

}<br />

The controllingExpression, which must be enclosed in parentheses, is evaluated once. Control then<br />

jumps to the block of code identified by the constantExpression whose value is equal to the result<br />

of the controllingExpression. (The constantExpression identifier is also called a case label.) Execution<br />

runs as far as the break statement, at which point the switch statement finishes and the program<br />

continues at the first statement that follows the closing brace of the switch statement. If none of the<br />

constantExpression values is equal to the value of the controllingExpression, the statements below the<br />

optional default label run.<br />

Note Each constantExpression value must be unique so that the controllingExpression<br />

will match only one of them. If the value of the controllingExpression does not match any<br />

constantExpression value and there is no default label, program execution continues with<br />

the first statement that follows the closing brace of the switch statement.<br />

So, you can rewrite the previous cascading if statement as the following switch statement:<br />

switch (day)<br />

{<br />

case 0 :<br />

dayName = "Sunday";<br />

break;<br />

case 1 :<br />

dayName = "Monday";<br />

break;<br />

case 2 :<br />

dayName = "Tuesday";<br />

break;<br />

...<br />

default :<br />

dayName = "Unknown";<br />

break;<br />

}<br />

100 PART I Introducing Microsoft Visual C# and Microsoft Visual Studio 2015

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!