User:Foxall/14

Ka Wiktionary

Hour 14. Making Decisions in C# Code[wax ka badal]

In [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch11.htm#ch11 Hour 11], "Creating and Calling Methods," you learned how to separate code into multiple methods to be called in any order required. But if you had to separate each small code routine into its own method, your projects would quickly become unmanageable. Instead of creating numerous methods, you can use decision-making techniques to execute or omit specific lines of code within a single method. Decision-making constructs or coding structures allow you to execute (or omit) code based on the current situation, such as the value of a variable. C# includes two constructs that allow you to make any type of branching decision you can think of: if…else and switch.

In this hour, you'll learn how to use the decision constructs provided by C# to perform robust yet efficient decisions in C# code. In addition, you'll learn how to use the goto statement to redirect code. You'll probably create decision constructs in every application you build, so the quicker you master these skills, the easier it will be to create robust applications.

The highlights of this hour include the following:

  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch14lev1sec1.htm#ch14lev1sec1 Making decisions using if statements]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch14lev1sec1.htm#ch14lev2sec1 Expanding the capability of if statements using else]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch14lev1sec2.htm#ch14lev1sec2 Evaluating an expression for multiple values using the switch statement]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch14lev1sec3.htm#ch14lev1sec3 Redirecting code flow using goto]

Making Decisions Using if Statements[wax ka badal]

By far the most common decision-making construct used in programming is the if construct. A simple if construct looks like this:

if (expression)
 ... statement to execute when expression is true;

The if construct uses Boolean logic, as discussed in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch13.htm#ch13 Hour 13], "Performing Arithmetic, String Manipulation, and Date/Time Adjustments," to evaluate an expression to either true or false. The expression may be simple (if (x == 6)) or complicated (if (x==6 && y>10)). If the expression evaluates to true, the statement or block of statements (if enclosed in braces) gets executed. If the expression evaluates to false, C# doesn't execute the statement or statement block for the if construct.

graphics/bookpencil.gif Remember that compound, also frequently called block statements, can be used anywhere a statement is expected. A compound statement consists of zero or more statements enclosed in braces ({}). Following is an example of the if construct using a block statement:
if (expression)
 {
 statement 1 to execute when expression is true;
 statement 2 to execute when expression is true;
 ... statement n to execute when expression is true;
 }

You're going to create a simple if construct in a C# project. Create a new Windows Application named Decisions. Rename the default form to fclsDecisions, set the Text property of the form to Decisions Example, and update the entry point Main() to reference fclsDecisions instead of Form1.

Add a new text box to the form by double-clicking the Textbox icon in the toolbox. Set the properties of the text box as follows:

Property Value
Name txtInput
Location 44,44
Text (make blank)

Next, add a new button to the form by double-clicking the Button icon in the toolbox. Set the button's properties as follows:

Property Value
Name btnIsLessThanHundred
Location 156,42
Size 100,23
Text Is text < 100?

Your form should now look like the one in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/14.htm#ch14fig01 Figure 14.1].

Figure 14.1. You'll use the if statement to determine whether the value of the text entered into the text box is less than 100.

graphics/14fig01.jpg

You're now going to add code to the button's Click event. This code will use a simple if construct and the int.Parse() method. The int.Parse() method is used to convert text into its numeric equivalent, and you'll use it to convert the text in txtInput into an integer. The if statement will then determine whether the number entered into the text box is less than 100. Double-click the button now to access its Click event, and enter the following code:

if (int.Parse(txtInput.Text)< 100 )
 MessageBox.Show("The text entered is less than 100.");

This code is simple when examined one statement at a time. Look closely at the first statement and recall that a simple if statement looks like this:

if (expression)
 statement; 

In the code you entered, expression is

int.Parse(txtInput.Text)< 100

What you are doing is asking C# to evaluate whether the parsed integer is less than 100. If it is, the evaluation returns true. If the value is greater than or equal to 100, the expression returns false. If the evaluation returns true, execution proceeds with the line immediately following the if statement and a message is displayed. If the evaluation returns false, the line statement (or block of statements) following the if statement doesn't execute and no message is displayed.

graphics/bookpencil.gif If the user leaves the text box empty or enters a string, an exception will be thrown. Therefore, you'd normally implement exception handling around this type of code. You'll learn about exception handling in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch16.htm#ch16 Hour 16], "Debugging Your Code."
Executing Code When Expression Is False 

If you want to execute some code when expression evaluates to false, include the optional else keyword, like this:

if (expression)
 statement to execute when expression is true;
else
 statement to execute when expression is false;
graphics/bookpencil.gif If you want to execute code only when expression equates to false, not when true, use the not-equal operator (!=) in the expression. Refer to [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch13.htm#ch13 Hour 13] for more information on Boolean logic.

By including an else clause, you can have one or more statements execute when expression is true and other statements execute when the expression is false. In the example you've built, if a user enters a number less than 100, the user will get a message. However, if the number is greater than or equal to 100, the user receives no feedback. Modify your code to look like the following, which ensures that the user always gets a message:

if (int.Parse(txtInput.Text)< 100 )
 MessageBox.Show("The text entered is less than 100.");
else
 MessageBox.Show("The text entered is greater than or equal to 100.");

Now, if the user enters a number less than 100, the message The text entered is less than 100 is displayed, but nothing more. When C# encounters the else statement, it ignores the statement(s) associated with the else statement. The statements for the else condition execute only when expression is false. Likewise, if the user enters text that is greater than or equal to 100, the message The text entered is greater than or equal to 100 is displayed, but nothing more; when expression evaluates to false, execution immediately jumps to the else statement.

Click Save All on the toolbar to save your work and then press F5 to run the project. Enter a number into the text box and click the button. A message box appears, telling you whether the number you entered is less than or greater than 100 (see [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/14.htm#ch14fig02 Figure 14.2]).

Figure 14.2. As implied with this message box, if gives you great flexibility in making decisions.

graphics/14fig02.jpg

Feel free to enter other numbers and click the button as often as you like. When you're satisfied that the code is working, choose Stop Debugging from the Debug menu.

graphics/bulb.gif Get comfortable with if; chances are you'll include at least one in every project you create.
Nesting if Constructs 

As mentioned earlier, you can nest if statements to further refine your decision making. The format you use can be something like the following:

if ( expression1 )
 if ( expression2 )
 ...
 else
 ...
else
 ...
>

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 [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/14.htm#ch14fig03 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 [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/14.htm#ch14fig04 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.

Branching Within Code Using goto
graphics/newterm.gif Decision structures are used to selectively execute code. When a decision statement is encountered, C# evaluates an expression and diverts code according to the result. You don't have to use a decision structure to divert code, however, because C# includes a statement that can be used to jump code execution to a predetermined location within the current procedure: the goto statement. Before I talk about how to use goto, I want to say that under most circumstances, it's considered bad coding practice to use a goto. Code that's heavily laden with gotos is difficult to read and debug because the execution path is so convoluted. Such code is often called spaghetti code, and should be avoided at all costs. I'd say that in 90% of the situations in which goto is used, a better approach to the problem exists, and I'll show an example of just such a case shortly. Nevertheless, goto, like all other statements, is a tool. Although it's not needed as often as some of the other C# statements are, it's still a useful tool to have at your disposal�when used judiciously.
graphics/newterm.gif To jump to a specific location in code, you must first define the jump location using a code label. A code label is not the same as a Label control that you place on a form. You create a code label by positioning the cursor on a new line in a method, typing in a name for the label followed by a colon, and pressing Enter. Code labels can't contain spaces and they can't be a C# reserved word. For instance, you can't create a code label called try, because try is a reserved word in C#. However, you could create a label called TryThis, because TryThis isn't a reserved word. Code labels act as pointers that you can jump to using goto. The following shows an example using goto to jump code execution to a label.
private void btnGoto_Click(object sender, System.EventArgs e)
{
 long lngCounter = 0;

IncrementCounter:
 lngCounter++;
 if (lngCounter < 5000) goto IncrementCounter;
}

This code does the following:

  • Dimensions a long variable called lngCounter.
  • Sets the new variable to 0.
  • Defines a code label titled IncrementCounter. One or more goto statements can be used to jump code execution to this label at any time.
  • Increments lngCounter by 1.
  • Uses an if statement to determine if lngCounter has exceeded 5000. If it hasn't, a goto statement forces code execution back to the IncrementCounter label, where lngCounter is incremented and tested again, creating a loop.

This code works, and you're welcome to try it. However, this is terrible code. Remember how I said that the use of a goto can often be replaced by a better coding approach? In this case, C# has specific looping constructs that you'll learn about in the next hour. These looping constructs are far superior to building your own loop under most conditions, so you should avoid building a loop using a goto statement. In fact, one of the biggest misuses of goto is using it in place of one of C#'s internal looping constructs. In case you're interested, here's the loop that would replace the use of goto in this example:

for(long lngCounter = 0; lngCounter<=5000; lngCounter++)
 ...

This discussion may leave you wondering why you would ever use goto. One situation in which I commonly use goto statements is to create single exit points. As you know, you can force execution to leave a method at any time using return. Often, clean-up code is required before a method exits. In a long method, you may have many return statements. However, such a method can be a problem to debug because clean-up code may not be run under all circumstances. Because all methods have a single entry point, it makes sense to give them a single exit point. With a single exit point, you use a goto statement to go to the exit point, rather than use a return statement. The following procedure illustrates using goto to create a single exit point:

private void btnGoto_Click(object sender, System.EventArgs e)
{
 ...
 ...
 // If it is necessary to exit the code, perform a goto to
 // the PROC_EXIT label, rather than using an Exit statement.
PROC_EXIT:
 ...
 return;
}
>

Summary

In this hour you learned how to use C#'s decision constructs to make decisions in C# code. You learned how to use if statements to execute code when an expression evaluates to true and to use else to run code when the expression evaluates to false. For more complicated decisions, you learned how to use else…if to add further comparisons to the decision construct and nest if structures for more flexibility.

In addition to if, you learned how to use switch to create powerful decision constructs to evaluate a single expression for many possible values. You learned how you can check for multiple possible values using a fall through case statement. Finally, you learned how to use goto to jump to any predefined position in code.

Decision-making constructs are often the backbone of applications. Without the capability to run specific sets of code based on fluctuating situations, your code would be very linear and hence very limited. Get comfortable with the decision constructs and make a conscious effort to use the best construct for any given situation. The better you are at writing decision constructs, the faster you'll be able to product solid and understandable code.

>

Q&A

[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/14.htm#qad1e45927 Q1:] What if I want to execute code only when an expression in an if statement is false, not true? Do I need to place the code in an else clause, and no code after the if?
A1: This is where Boolean logic helps. What you need to do is make the expression evaluate to true for the code you want to run. This is accomplished using the not operator (!) in the expression, like this:
if (!expression)<br />. . .<br />
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/14.htm#qad1e45943 Q2:] How important is the order in which case statements are created?
A2: This all depends on the situation. In the example given in the text in which the selected animal was considered and the number of legs it has was displayed, the order of the Dog case was important. If all case statements contained code, the order has no effect.

Workshop

The Workshop is designed to help you anticipate possible questions, review what you've learned, and get you thinking about how to put your knowledge into practice. The answers to the quiz are in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01.htm#app01 Appendix A], "Answers to Quizzes/Exercises."

 Quiz
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec14.htm#ch14ans01 1:] Which decision construct should you use to evaluate a single expression to either true or false?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec14.htm#ch14ans02 2:] Evaluating expressions to true or false for both types of decision constructs is accomplished using ________ logic.
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec14.htm#ch14ans03 3:] If you want code to execute when the expression of an if statement evaluates to false, include an ____ clause.
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec14.htm#ch14ans04 4:] Which decision construct should you use when evaluating the result of an expression that may equate to one of many possible values?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec14.htm#ch14ans05 5:] Is it possible that more than one case statement may have its code execute?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec14.htm#ch14ans06 6:] True or False: You can use goto to jump code execution to a different method.
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec14.htm#ch14ans07 7:] To use goto to jump execution to a new location in code, what must you create as a pointer to jump to?
Exercises
  1. Create a project that allows the user to enter text into a text box. Use an if construct to determine whether the text entered is Circle, Triangle, Square, or Pentagon, and display the number of sides the entered shape has. If the text doesn't match one of these shapes, let the users know that they must enter a shape.
  2. Rewrite the following code using only an if structure; the new code should not contain a goto.
...
if (!blnAddToAge) goto SkipAddToAge;
lngAge++;
SkipAddToAge:
...