Commands: Conditional

Unlike many programming languages, Visual Basic has been designed to focus on readability and clarity. Many languages are willing to sacrifice these attributes. Visual Basic is designed under the paradigm that the readability of code matters, so commands in Visual Basic tend to spell out the exact context of what is being done.

Literally dozens of commands make up the Visual Basic language, so there isn't nearly enough space here to address all of them. Moreover, many of the more specialized commands are covered later in this book. However, in case you are not familiar with Visual Basic or are relatively new to programming, this book will touch on a few of these. In this chapter, it makes the most sense to review the syntax of conditional statements.

Each of these statements has the ability to literally encapsulate a block of code. Of course the preferred way of embedding code within the scope of a conditional or loop is to call another method. Using a method within your loop or conditional helps keep your structure apparent and simple to view, and allows for code reuse if the same actions need to be accomplished from another location within your code.

Note that the variables declared within the context of a conditional statement (between the If and End If lines) are available only up until the End If statement. After that, these variables go out of scope. The concept of scoping is discussed in more detail later in this chapter.

If Then

The conditional is one of two primary programming constructs (the other being the loop) that is present in almost every programming language. Visual Basic supports the If- Then statement as well as the Else statement, and unlike some languages, the concept of an ElseIf statement. The ElseIf and Else statements are totally optional, and it is not only acceptable but common to use conditionals that do not utilize either of these code blocks. The following example illustrates a simple pair of conditions that have been set up serially:

If i > 1 Then
    'Code A1
ElseIf i < 1 Then
    'Code B2
Else
    'Code C3
End If

If the first condition is true, then code placed at marker A1 is executed. The flow would then proceed to the End If, and the program would not evaluate any of the other conditions. Note that for best performance, it makes the most sense to have your most common condition first in this structure, because if it is successful, none of the other conditions need to be tested.

If the initial comparison in the preceding example code were false, then control would move to the first Else statement, which in this case happens to be an ElseIf statement. The code would therefore test the next conditional to determine whether the value of i were less than 1. If so, then the code associated with block B2 would be executed.

However, if the second condition were also false, then the code would proceed to the Else statement, which isn't concerned with any remaining condition and just executes the code in block C3. Not only is the Else optional, but even if an ElseIf is used, the Else condition is still optional. It is acceptable for the Else and C3 block to be omitted from the preceding example.

Comparison Operators

Essentially, the code between the If and Then portions of the statement must eventually evaluate out to a Boolean. At the most basic level, this means you can write If True Then, which results in a valid statement that would always execute the associated block of code with that If statement. The idea, however, is that for a basic comparison, you take two values and place between them a comparison operator. Comparison operators include the following symbols: =, >, <, >=, <=.

Additionally, certain keywords can be used with a comparison operator. For example, the keyword Not can be used to indicate that the reversal of a Boolean result. Note that with Visual Basic the Not conditional is simply placed before the comparions to which it will be applied. An example of this is shown in the next example:

If Not i = 1 Then
    'Code A1
End If

In this case, the result is only reversed so code at marker A1 is executed whenever i does not equal 1. The If statement supports complex comparisons and leveraging boolean statements such as And and Or. These statements enable you to create a complex condition based on several comparisons, as shown here:

If Not i = 1 Or i < 0 And str = "Hello" Then
    'Code A1
Else
    'Code B2
End If

The And and Or conditions are applied to determine whether the first comparison's results are true or false along with the second value's results. The And conditional means that both comparisons must evaluate to true in order for the If statement to execute the code in block A1, and the Or statement means that if the condition on either side is true, then the If statement can evaluate code block A1. However, in looking at this statement, your first reaction should be to pause and attempt to determine in exactly what order all of the associated comparisons occur.

Visual Basic applies conditions based on precedence. First, any numeric style comparisons are applied, followed by any unary operators such as Not. Finally, proceeding from left to right, each Boolean comparison of And and Or is applied. However, a much better way to write the preceding statement is to use parentheses to identify in what order you want these comparisons to occur. The first If statement in the following example illustrates the default order, while the second and third use parentheses to force a different priority on the evaluation of the conditions:

If ((Not i = 1) Or i < 0) And (str = "Hello") Then
If (Not i = 1) Or (i < 0 And str = "Hello") Then
If Not ((i = 1 Or i < 0) And str = "Hello") Then

All three of the preceding If statements are evaluating the same set of criteria, yet their results are potentially very different. It is always best practice to enclose complex conditionals within parentheses to indicate the desired order of evaluation. Of course, these comparisons have been rather simple; you could replace the variable value in the preceding examples with a function call that might include a call to a database. In such a situation, since the method execution might have a higher performace cost you might want to use one of the shortcut comparison operators.

Typically Visual Basic always evaluates both sides of a condition. But you know that for an And statement both sides of the If statement must be true. Thus there are times when knowing that the first condition is false means you don't need to evaluate the other side of the And statement. Bypassing this could save processing time; you would not bother executing the second condition. Similarly, if the comparison involves an Or statement, then once the first part of the condition is true, there is no reason to evaluate the second condition, because you know that the net result is success. In these cases, Visual Basic provides the AndAlso and OrElse conditionals to allow for performance optimization:

If ((Not i = 1) Or i < 0) AndAlso (MyFunction() = "Success") Then
If Not i = 1 OrElse (i < 0 And MyFunction() = "Success") Then

The preceding code illustrates that instead of using a variable your condition might call a function you've written that returns a value. In the preceding statements, each conditional statement has been optimized so that there are situations where the code associated with MyFunction won't be executed.

This is potentially important, not only from a performance standpoint, but also in a scenario where, given the first condition, your code might throw an error. For example, it's not uncommon to first determine whether a variable has been assigned a value and then to test that value. Once you know the value doesn't exist it is erroneous to check that value.

However, not all values are primitive types; thus to determine if a reference type has a value Visual Basic provides an additional pair of conditional elements: the Is and IsNot conditionals.

Using Is and IsNot enables you to determine whether a variable has been given a value, or to determine its type. In the past it was common to see nested If statements, with the first determining whether the value was Nothing, followed by a separate If statement to determine whether the value was valid. Starting with .NET 2.0, the short-circuit conditionals enable you to check for a value and then check whether that value meets the desired criteria. The short-circuit operator prevents the check for a value from occurring and causing an error if the variable is undefined, so both checks can be done with a single If statement:

Dim mystring as string = Nothing
If mystring IsNot Nothing AndAlso mystring.Length > 100 Then
    'Code A1
ElseIf mystring.GetType Is GetType(Integer) Then
    'Code B2
End If

The preceding code will fail on the first condition because mystring has been initialized to Nothing, meaning that by definition it doesn't have a length. Note also that the second condition will fail because you know that myString isn't of type Integer.

Select Case

The preceding section makes it clear that the If statement is the king of conditionals. However, in another scenario you may have a simple condition that needs to be tested repeatedly. For example, suppose a user selects a value from a drop-down list and different code executes depending on that value. This is a relatively simple comparison, but if you have 20 values, then you would potentially need to string together 20 different If Then and ElseIf statements to account for all of the possibilities.

A cleaner way of evaluating such a condition is to leverage a Select Case statement. This statement was designed to test a condition, but instead of returning a Boolean value, it returns a value that is then used to determine which block of code, each defined by a Case statement, should be executed:

Select Case i
    Case 1
       'Code A1
    Case 2
       'Code B2
    Case Else
       'Code C3
End Select

The preceding sample code shows how the Select portion of the statement determines the value represented by the variable i. Depending on the value of this variable, the Case statement executes the appropriate code block. For a value of 1, the code in block A1 is executed; similarly, a 2 results in code block B2 executing. For any other value, because this Case statement includes an Else block, the Case statement executes the code represented by C3. Note that while in this example each item has its own block, it is also possible to have more than a single match on the same Case. Thus Case 2, 3 would match if the value of i were either a 2 or a 3. Finally, the next example illustrates that the cases do not need to be integer values, and can, in fact, even be strings:

Dim mystring As String = "Intro"
Select Case mystring
    Case "Intro"
        'Code A1
    Case "Exit"
        'Code A2
    Case Else
        'Code A3
End Select

Now that you have been introduced to these two control elements that enable you to specify what happens in your code, your next step is to review details of the different variable types that are available within Visual Basic 2012, starting with the value types.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset