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 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. C# includes a much better decision construct for evaluating a single expression for multiple possible values: switch.

A switch construct looks like the following:

  switch (  expression  )   {   case  value1  :  ...          jump-statement  default:  ...          jump-statement  }  
graphics/bookpencil.gif

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 currently not supported 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.

graphics/bookpencil.gif

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 expression evaluation in a switch construct. This simple application will display a list of animals in a combo box to the user. When the user clicks a button, the application will display the number of legs of the animal in the list (if an animal is selected). Create a new Windows Application named Switch Example. Rename the default form to flcsSwitchExample, set the form's Text property to Switch Example, and update the entry point in procedure Main() to reference flcsSwitchExample instead of Form1.

Next, 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
Text (make blank)

Next, you'll 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 14.3; be sure to press Enter at the end of each list item to make the next item appear on its own line.

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

graphics/14fig03.jpg


Next you'll add a Button control. When the button is clicked, a switch construct will be used to determine which animal the user has 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,140
Text Show Legs

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

Figure 14.4. This example uses only a combo box and a button control.

graphics/14fig04.jpg


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 "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; } 
graphics/newterm.gif

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, C# looks to see if the content is "Dog," and so on. Notice that the Dog case contains no code, therefore the execution of the code in the following case (Cat) is executed if the text Dog was selected (this is known as execution falling through ). In this situation, 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 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.

Press F5 to run your project now and give it a try. Select an animal from the list and click the button. Try clearing the contents of the combo box and clicking the button. When you're finished, choose Stop Debugging from the Debug menu to stop the project and click Save All on the toolbar.


   
Top


Sams Teach Yourself C# in 24 Hours
Sams Teach Yourself Visual Basic 2010 in 24 Hours Complete Starter Kit (Sams Teach Yourself -- Hours)
ISBN: 0672331136
EAN: 2147483647
Year: 2002
Pages: 253
Authors: James Foxall

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