Understanding If Statements

function OpenWin(url, w, h) { if(!w) w = 400; if(!h) h = 300; window.open(url, "_new", "width=" + w + ",height=" + h + ",menubar=no,toobar=no,scrollbars=yes", true); } function Print() { window.focus(); if(window.print) { window.print(); window.setTimeout('window.close();',5000); } }
Team-Fly    

Special Edition Using Microsoft® Visual Basic® .NET
By Brian Siler, Jeff Spotts
Table of Contents
Chapter 7.  Controlling the Flow of Your Program


For many decisions, you may want to execute a statement (or group of statements) only if a particular condition is True. Two forms of the If statement handle True conditions: the single-line If statement and the multiple-line If statement. Each uses the If statement to check a condition. If the condition is True, the program runs the commands associated with the If statement. For example, the following two If statements perform the same function:

 'Single-Line IF  If x > 5 then x = 0  'Multiple-Line IF  If x > 5 Then      x = 0  End If 

In the code sample, the condition is the value of the variable x being greater than 5. If this condition is True the statement x=0 will be executed. If the condition is False (in the preceding example, if x is not greater than 5), the commands on the If line (single-line If) or between the If and End If statements (multiple-line If) are skipped, and the next line of code is executed.

The Single-Line If Statement

You use the single-line If statement to perform a single task when the condition in the statement is True. The task can be a single command, or you can perform multiple commands by calling a procedure. The following is the syntax of the single-line If statement:

 If condition Then command 

The argument condition represents any type of logical condition, which can be any of the following:

  • Comparison of a variable to a literal, another variable, or a function

  • A variable or database field that contains a True or False value

  • Any function or expression that returns a True or False value

The argument command represents the task to be performed if the condition is True. This task can be any valid Visual Basic statement, including a procedure call. The following code shows how an If statement is used to display a message only if the statement is executed before the noon hour:

 If Date.Now.Hour < 12 Then Messagebox.Show("Good morning!") 

Using Multiple Commands with an If Block

If you need to execute more than one command in response to a condition, you can use the multiple-line form of the If statement. It also is known as a block If statement. This construct bounds a range of statements between the If statement and an End If statement. If the condition in the If statement is True, all the commands between the If and End If statements are executed. If the condition is False, the program skips to the first line after the End If statement. The following example shows how a block If statement is used in processing a market exhibitor's payments. If the exhibitor has a deposit on file, the deposit amount is moved to the total amount paid, and a procedure that processes a reservation is called.

 If DepositAmt > 0 Then      TotalPaid = TotalPaid + DepositAmt      DepositAmt = 0      UpdateReservation(ExhibitorID)  End If 

Note that indenting lines of code in a multiple-line If statement is a customary formatting practice that makes the code more readable. As you type a multi-line If statement in the code editor, Visual Basic .NET automatically indents the code contained in an If block and adds the End If when you type the word Then and press Enter. This feature can be disabled under the "Visual Basic Specific Options" section in the Text Editor Folder of the Options dialog box.

Note

Many programmers never use the single-line format of the If statement, preferring the readability and structure of the block If.


Working with the False Condition

Of course, if a condition can be True, it also can be False; and sometimes you might want code to execute only on a False condition. Other times, you might want to take one action if a condition is True and another action if the condition is False. The following sections look at handling the False side of a condition.

Using the Not Operator

One way to execute a statement, or group of statements, for a False condition is to use the Not operator. The Not operator inverts the actual condition that follows it. If the condition is True, the Not operator makes the overall expression False, and vice versa. The following code uses the Not operator to invert the value of the Boolean variable Taxable, which reports an exhibitor's sales and use tax status. Taxable is True if the exhibitor is to pay taxes, and False if he or she is not. The code tests for the condition Not Taxable; if this condition evaluates to True, the exhibitor is not taxable.

 If Not Taxable Then      SalesTax = 0      UseTax = 0  End If 
Handling True and False Conditions with Else

The other way of handling False conditions allows you to process different sets of instructions for the True or False condition. You can handle this "fork in the road" in Visual Basic with the Else part of the If statement block.

To handle both the True and False conditions, you start with the block If statement and add the Else statement, as follows:

 If condition Then     statements to process when condition is True  Else     statements to process when condition is False  End If 

The If and End If statements of this block are the same as before. The condition is still any logical expression or variable that yields a True or False value. The key element of this set of statements is the Else statement. This statement is placed after the last statement to be executed if the condition is True, and before the first statement to be executed if the condition is False. For a True condition, the program processes the statements up to the Else statement and then skips to the first statement after the End If. If the condition is False, the program skips the statements prior to the Else statement and starts processing with the first statement after the Else.

Note

If you want to execute code for only the False portion of the statement, you can just place code statements between the Else and End If statements. You are not required to place any statements between the If and Else statements.


Tip

If you have several commands between the If and End If statements, you might want to repeat the condition as a comment in the End If statement, as in this example:

 If TotalSales > ProjectedSales Then          '          ' A bunch of lines of code          '  Else          '          ' Another bunch of lines of code          '  End If  'TotalSales > ProjectedSales 

Adding this comment makes your code easier to read.


Working with Multiple If Statements

In the preceding sections, you saw the simple block If statements, which evaluate one condition and can execute commands for either a True or a False condition. You also can evaluate multiple conditions with an additional statement in the block If. The ElseIf statement enables you to specify another condition to evaluate when the first condition is False. Using the ElseIf statement, you can evaluate any number of conditions with one If statement block. The following lines of code demonstrate how you can use ElseIf to test for three possibilities whether the contents of the variable TestValue are negative, zero, or positive:

 If TestValue < 0 Then          lblResult.Text = "Negative"      ElseIf TestValue = 0 Then          lblResult.Text = "Zero"      Else          lblResult.Text = "Positive"      End If 

The preceding code works by first evaluating the condition in the If statement. If the condition is True, the statement (or statements) immediately following the If statement is executed; then the program skips to the first statement after the End If statement.

If the first condition is False, the program skips to the first ElseIf statement and evaluates its condition. If this condition is True, the statements following the ElseIf are executed, and control again passes to the statement after the End If. This process continues for as many ElseIf statements as are in the block.

If all the conditions are False, the program skips to the Else statement and processes the commands between the Else and the End If statements. The Else statement is not required.

Using Boolean Logic in If Conditions

Often you will use the standard If..Then..Else syntax, which is easy to understand because it reads like a sentence from a book. However, there are a couple of special situations that you may encounter when using the If construct that are worth mentioning:

  • Logical operators can cause problems if not used correctly.

  • Short-circuiting works with Boolean conditions to eliminate extra work.

The result of the evaluation of an If condition is a True or False value. As you may have noticed in previous examples, Boolean operators such as And, Or, and Not can be used to build more complex expressions from smaller ones:

 If (WeeklyHrs > 30 And HireDate < Date.Now.AddYears(-1)) Or Status = "FullTime"  Then     EligibleForBenefits = True  Else     EligibleForBenefits = False  End If 

The previous If statement could be stated as follows in plain English:

"In order to be eligible for benefits, you must either be a full-time employee or work more than 30 hours a week and have been hired for over a year."

Note the use of parentheses to group logical conditions, such that the result of the And comparison is evaluated and that result is used in the Or condition. The logical operators used with True/False conditions are as follows:

  • And Expressions on both sides of the And must evaluate True for the result to be True. If one or more expressions in the And comparison is False, the result is False.

  • Or If either side of an Or comparison is True, or both sides are True, then the result is True. The result of an Or is False only if both expressions are False.

  • Xor This stands for exclusive or. This operator is similar to Or but False if both sides are True. It can be read in English as "one or the other but not both."

  • Not Negates theresult of an expression, Not True is False and Not False is True.

A common mistake is to use Or when you really mean And. For example, if a computer dating service is looking for single females over 21, this could cause quite a problem:

 'Probably not what the programmer intended!  If Age >= 21 Or Sex = "F" Or Married = False Then 

In the previous expression, if any one of the above expressions is True, the statements in the If will be executed. For example, a married 20-year-old lady or a two-year-old baby boy would cause the Or condition to evaluate to True. When you want multiple conditions to be required, And is usually the correct choice.

Another interesting aspect of Boolean expressions is the fact that you can often determine the result without looking at the whole expression. For example, with an And condition both sides must be True for the expression to be True; therefore if the left side of an And evaluates to False, you can assume the entire statement is False. This concept is known as short-circuiting, because you do not have to evaluate the whole expression. Short-circuiting was not supported in Visual Basic 6.0, but is supported in Visual Basic .NET. Every programmer should be aware of this concept, which is used to avoid unnecessary processing when using Boolean expressions:

 If Process1BillionRecords() And Process1BillionMore() Then 

Because of short-circuiting, if the Process1BillionRecords function returns False, the second function call would never be executed. Usually, you would not want to process an extra billion records (which we assume will take some time) because the expression is already known to be False. Most of the time short-circuiting works in your favor, but if you actually count on a function being executed in an If statement no matter what its return value, you may want to store the result of each call in a Boolean variable and then use And to compare the variables.


    Team-Fly    
    Top
     



    Special Edition Using Visual Basic. NET
    Special Edition Using Visual Basic.NET
    ISBN: 078972572X
    EAN: 2147483647
    Year: 2001
    Pages: 198

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