Making Decisions Using if Statements

   

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 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 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 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 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 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    ... 

   
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