Evaluating an Expression for Multiple Values Using switch


Evaluating an Expression for Multiple Values Using switch

At times, the if construct isn't capable of handling a decision situation without a lot of extra work. One such situation is when you need to perform different actions based on numerous possible values of an expression, not just true or false. For instance, suppose that you wanted to perform actions based on a user's profession. The following shows what you might create using if:

if (strProfession =="programmer")    ... else if (strProfession =="teacher")    ... else if (strProfession =="accountant")    ... else    ...


As you can see, this structure can be a bit hard to read. If the number of supported professions increases, this type of construction will get harder to read and debug. In addition, executing many if statements like this is rather inefficient from a processing standpoint.

The important thing to realize here is that each else...if is really evaluating the same expression (strProfession) but considering different values for the expression. Visual C# includes a much better decision construct for evaluating a single expression for multiple possible values: switch.

A basic switch construct looks like the following:

switch (expression) {    case value1:            ...         jump-statement    default:            ...         jump-statement }


By the Way

default is used to define code that executes only when expression doesn't evaluate to any of the values in the case statements. Use of default is optional.


Here's the Profession example shown previously, but this time switch is used:

switch (strProfession) { case "teacher":         MessageBox.Show("You educate our young");         break;     case "programmer":         MessageBox.Show("You are most likely a geek");         break;     case "accountant":         MessageBox.Show("You are a bean counter");         break;     default:         MessageBox.Show("Profession not found in switch statement");         break; }


The flow of the switch statement is as follows: When the case expression is matched, the code statement or statements within the case are executed. This must be followed by a jump statement, such as break, to transfer control out of the case body.

By the Way

If you create a case construct but fail to put code statements or a jump-statement within the case, execution will fall through to the next case statement, even if the expression doesn't match.


The switch makes decisions much easier to follow. Again, the key with switch is that it's used to evaluate a single expression for more than one possible value.

Building a switch Example

You're now going to build a project that uses advanced expression evaluation in a switch structure. This simple application displays a list of animals to the user in a combo box. When the user clicks a button, the application displays the number of legs of the animal chosen in the list (if an animal is selected). Start by creating a new Windows Application named Switch Example and then follow these steps:

1.

Right-click Form1.cs in the Solution Explorer, choose Rename, and then change the name of the form to frmSwitchExample.cs. Next, set the form's Text property to Switch Example (you'll have to click the form once to view its design properties).

2.

Add a new combo box to the form by double-clicking the ComboBox item on the toolbox. Set the combo box's properties as follows:

Property

Value

Name

cboAnimals

Location

80,100


3.

Next, add some items to the list. Click the Items property of the combo box, and then click the Build button that appears in the property to access the String Collection Editor for the combo box. Enter the text as shown in Figure 13.3; be sure to press Enter at the end of each list item to make the next item appear on its own line.

Figure 13.3. Each line you enter here becomes an item in the combo box at runtime.


4.

Add a Button control. When the button is clicked, a switch construct is used to determine which animal the user selected and to tell the user how many legs the selected animal has. Add a new button to the form by double-clicking the Button tool in the toolbox. Set the button's properties as follows:

Property

Value

Name

btnShowLegs

Location

102,130

Text

Show Legs


Your form should now look like the one in Figure 13.4. Click Save All on the toolbar to save your work before continuing.

Figure 13.4. This example uses only a combo box and a Button control.


All that's left to do is add the code. Double-click the Button control to access its Click event and then enter the following code:

switch (cboAnimals.Text) {    case "Bird":       MessageBox.Show("The animal has 2 legs.");       break;    case "Dog":       // Notice there is no code here to execute.    case "Horse":       // Notice there is no code here to execute.    case "Cat":       MessageBox.Show("The animal has 4 legs.");       break;    case "Snake":       MessageBox.Show("The animal has no legs.");       break;    case "Centipede":       MessageBox.Show("The animal has 100 legs.");       break;    default:       MessageBox.Show("You did not select from the list!");       break; }


Here's what's happening:

  • The switch construct compares the content of the cboAnimals combo box to a set of predetermined values. Each case statement is evaluated in the order in which it appears in the list. Therefore, the expression is first compared to "Bird." If the content of the combo box is Bird, the MessageBox.Show() method immediately following the case statement is called, followed by the break statement, which transfers control outside of the switch construct.

  • If the combo box doesn't contain Bird, Visual C# looks to see if the content is "Dog," and so on. Notice that the Dog case contains no code. When a case statement has no code, the execution of the code in the following case is executed. In this situation, that would be (Horse), which also has no code. Visual C# continues down the list of case statements until it finds one with code and uses that. In this example, that would be the code for (Cat). This is known as execution falling through, and it's used to allow you to create one set of code that can be used for multiple case situations. In this example, you end up with the correct output. However, what happens if you move the Snake case in front of Cat? You'd end up telling the user that the dog has no legs! When using this technique, you must be careful that all situations will produce the desired behavior.

  • Each successive case statement is evaluated in the same way. If no matches are found for any of the case statements, the MessageBox.Show() method in the default statement is called. If there were no matches and no default statement, no code would execute.

As you can see, adding a new animal to the list can be as simple as adding a case statement.

Try it now by pressing F5 to run the project and then follow these steps:

1.

Select an animal from the list and click the button.

2.

Try clearing the contents of the combo box and clicking the button.

3.

When you're finished, choose Debug, Stop Debugging to stop the project, and click Save All on the toolbar.




Sams Teach Yourself Microsoft Visual C# 2005 in 24 Hours, Complete Starter Kit
Sams Teach Yourself Visual C# 2005 in 24 Hours, Complete Starter Kit
ISBN: 0672327406
EAN: 2147483647
Year: N/A
Pages: 248
Authors: James Foxall

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net