switch
Multiple-Selection StatementWe discussed the if
and if
…else
selection statements in Chapter 5. C# provides the switch
multiple-selection statement to perform different actions based on the possible values of an expression, known as the switch
expression. Each action is associated with one or more of the switch
expression’s possible values. These are specified as constant integral expressions or a constant string
expressions:
A constant integral expression is any expression involving character and integer constants that evaluates to an integer value—i.e., values of type sbyte
, byte
, short
, ushort
, int
, uint
, long
, ulong
and char
, or a constant from an enum
type (enum
is discussed in Section 7.9).
A constant string
expression is any expression composed of string
literals or const string
variables that always results in the same string
.
switch
Statement to Count A, B, C, D and F GradesFigure 6.9 calculates the class average of a set of numeric grades entered by the user, and uses a switch
statement to determine whether each grade is the equivalent of an A, B, C, D or F and to increment the appropriate grade counter. The program also displays a summary of the number of students who received each grade.
Lines 9 and 10 declare and initialize to 0 local variables total
and gradeCounter
to keep track of the sum of the grades entered by the user and the number of grades entered, respectively. Lines 11–15 declare and initialize to 0 counter variables for each grade category. The Main
method has two key parts. Lines 21–52 read an arbitrary number of integer grades from the user using sentinel-controlled iteration, update variables total
and gradeCounter
, and increment an appropriate letter-grade counter for each grade entered. Lines 54–76 output a report containing the total of all grades entered, the average grade and the number of students who received each letter grade.
Lines 17–19 prompt the user to enter integer grades and to type Ctrl + z, then press Enter to terminate the input. The notation Ctrl + z means to hold down the Ctrl key and tap the z key when typing in a Command Prompt. Ctrl + z is the Windows key sequence for typing the end-of-file indicator. This is one way to inform an app that there’s no more data to input. If Ctrl + z is entered while the app is awaiting input with a ReadLine
method, null
is returned. (The end-of-file indicator is a system-dependent keystroke combination. On many non-Windows systems, end-of-file is entered by typing Ctrl + d.) In Chapter 17, Files and Streams, we’ll see how the end-of-file indicator is used when an app reads its input from a file. Windows typically displays the characters ^Z
in a Command Prompt when the end-of-file indicator is typed, as shown in the program’s output.
Line 21 uses Console
’s ReadLine
method to get the first line that the user entered and store it in variable input
. The while
statement (lines 24–52) processes this user input. The condition at line 24 checks whether the value of input
is null
—Console
’s ReadLine
method returns null
only if the user typed an end-of-file indicator. As long as the end-of-file indicator has not been typed, input
will not be null
and the condition will pass.
Line 26 converts the string
in input
to an int
type. Line 27 adds grade
to total
. Line 28 increments gradeCounter
.
The switch
statement (lines 31–49) determines which counter to increment. In this example, we assume that the user enters a valid grade in the range 0–100. A grade in the range 90–100 represents A, 80–89 represents B, 70–79 represents C, 60–69 represents D and 0–59 represents F. The switch
statement consists of a block that contains a sequence of case
labels and an optional default
label. These are used in this example to determine which counter to increment based on the grade.
switch
StatementWhen control reaches the switch
statement, the app evaluates the expression grade / 10
in the parentheses—this is the switch
expression. The app attempts to match the value of the switch
expression with one of the case
labels. The switch
expression in line 31 performs integer division, which truncates the fractional part of the result. Thus, when we divide any value in the range 0–100 by 10, the result is always a value from 0 to 10. We use several of these values in our case
labels. For example, if the user enters the integer 85
, the switch
expression evaluates to int
value 8
. If a match occurs between the switch
expression and a case
(case 8:
at line 37), the app executes the statements for that case
. For the integer 8
, line 38 increments bCount
, because a grade in the 80s is a B.
The break
statement (line 39) causes program control to proceed with the first statement after the switch
(line 51), which reads the next line entered by the user and assigns it to the variable input
. Line 52 marks the end of the body of the while
statement that inputs grades, so control flows to the while
’s condition (line 24) to determine whether the loop should continue executing based on the value just assigned to the variable input
.
case
LabelsThe switch
’s case
s explicitly test for the values 10
, 9
, 8
, 7
and 6
. Lines 33–34 test for the values 9
and 10
(both of which represent the grade A). Listing case
labels consecutively in this manner with no statements between them enables the case
s to perform the same set of statements—when the switch
expression evaluates to 9
or 10
, the statements in lines 35–36 execute. The switch
statement does not provide a mechanism for testing ranges of values, so every value to be tested must be listed in a separate case
label. Each case
can have multiple statements. The switch
statement differs from other control statements in that it does not require braces around multiple statements in each case
.
default
CaseIf no match occurs between the switch
expression’s value and a case
label, the statements after the default
label (lines 47–48) execute. We use the default
label in this example to process all switch
-expression values that are less than 6
—that is, all failing grades. If no match occurs and the switch
does not contain a default
label, program control simply continues with the first statement (if there’s one) after the switch
statement.
Although each case
and the default
label in a switch
can occur in any order, place the
switch
StatementIn many other programming languages containing switch
, the break
statement is not required at the end of a case
. In those languages, without break
statements, each time a match occurs in the switch
, the statements for that case
and subsequent case
s execute until a break
statement or the end of the switch
is encountered. This is often referred to as “falling through” to the statements in subsequent case
s. This leads to logic errors when you forget the break
statement. C# is different from other programming languages—after the statements in a case
, you’re required to include a statement that terminates the case
, such as a break
, a return
or a throw
;1 otherwise, a compilation error occurs.2
Lines 54–76 output a report based on the grades entered (as shown in the input/output window in Fig. 6.9). Line 57 determines whether the user entered at least one grade—this helps us avoid dividing by zero. If so, line 60 calculates the average of the grades. Lines 63–71 then output the total of all the grades, the class average and the number of students who received each letter grade. If no grades were entered, line 75 outputs an appropriate message. The output in Fig. 6.9 shows a sample grade report based on 10 grades.
switch
Statement UML Activity DiagramFigure 6.10 shows the UML activity diagram for the general switch
statement. Every set of statements after a case
label normally ends its execution with a break
or return
statement to terminate the switch
statement after processing the case
. Typically, you’ll use break
statements. Figure 6.10 emphasizes this by including break
statements in the activity diagram. The diagram makes it clear that the break
statement at the end of a case
causes control to exit the switch
statement immediately.
case
of a switch
In the switch
statements cases, constant integral expressions can be character constants— specific characters in single quotes, such as 'A'
, '7'
or '$'
—which represent the integer values of characters. (Appendix C shows the integer values of the characters in the ASCII character set, which is a popular subset of the Unicode character set used by C#.) A string
constant (or string
literal) is a sequence of characters in double quotes, such as "Welcome to C# Programming!"
or a const string
variable. For string
s, you also can use null
or string.Empty
.
The expression in each case
also can be a constant—a value which does not change for the entire app. Constants are declared with the keyword const
(discussed in Chapter 7). C# also has a feature called enumerations, which we also present in Chapter 7. Enumeration constants also can be used in case
labels. In Chapter 12, we present a more elegant way to implement switch
logic—we use a technique called polymorphism to create apps that are often clearer, easier to maintain and easier to extend than apps using switch
logic.