JavaScript Editor JavaScript Editor     JavaScript Debugger

Previous Section Next Section

Main Page

Making Decisions with IfElse Statements

How can you make choices in your code, deciding what to do next depending on the values in your variables? You can use the If statement, which is the bread-and-butter of Visual Basic conditionals, and which lets you evaluate your data and execute appropriate code. Here's how this statement works:

If condition Then
[ElseIf condition-n Then
   [elseifstatements] ]
End If

You use comparison operators in the condition here to generate a logical result that's true or false; for example, if condition is intVariable > 5, then condition will be true if the value in intVariable is greater than 5.

If condition is True, the statements immediately following the Then keyword in the body of the If statement will be executed, and the If statement will terminate before the code in any ElseIf or Else statement is executed. If condition is False, the following ElseIf statements are evaluated, if there are any; this statement lets you test additional conditions, and if any are True, the corresponding code (elseifstatements above) is executed and the If statement terminates. If there are no ElseIf statements, or if none of their conditions are True, the code in the Else statement (elsestatements above), if there is one, is executed automatically.

Here's an example to show you how to use the various parts of this popular statement. In this case, I'm reading an integer that the user types at the console—using the System.Console.ReadLine method—and checking it against various values:

Module Module1
    Sub Main()
        Dim intInput As Integer
        System.Console.WriteLine("Enter an integer")
        intInput = Val(System.Console.ReadLine())
        If intInput = 1 Then
            System.Console.WriteLine("Thank you.")
        ElseIf intInput = 2 Then
            System.Console.WriteLine("That's fine.")
        ElseIf intInput = 3 Then
            System.Console.WriteLine("Too big.")
            System.Console.WriteLine("Not a number I know.")
        End If
    End Sub
End Module

Note that when you compare strings, not numbers, in condition, the string expressions are evaluated on the basis of their alphabetical sort order by default. The sort order for strings is evaluated based upon the Option Compare setting (see the In Depth section "The Option and Imports Statements" of this chapter). You can also use the String.Compare method to compare strings.

Also note that you can also use the TypeOf and Is keywords to check the type of an object in an If statement, like this:

If (TypeOf Err.GetException() Is OverflowException) Then
    System.Console.WriteLine("Overflow error!")
End If
Previous Section Next Section

JavaScript Editor Free JavaScript Editor     JavaScript Editor