Commands


Unlike many programming languages, Visual Basic has been designed to focus on readability and clarity. Many languages are willing to sacrifice these attributes in order to allow developers to type as little as possible. Visual Basic, conversely, is designed under the paradigm that the readability of code matters more than saving a few keystrokes, 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, if you are not familiar with Visual Basic or are relatively new to programming, a few would be helpful to look at here. These fall into two basic areas: conditional statements and looping statements. This section addresses two statements within each of these categories.

Each of these statements has the ability not only to call another method, the preferred way to manage blocks of code, but also to literally encapsulate a block of code. As noted in the rules on scoping, the blocks of encapsulated code within these commands can declare variables local to that block and can act in many ways like an unnamed method call.

If Then

The conditional is one of two primary programming constructs (the other being the loop) that is present in almost every programming language. After all, even in those rare cases where the computer is just repeatedly adding values or doing some other repetitive activity, at some point a decision will be needed and a condition evaluated, even if the question is only “is it time to stop?” 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 encounter 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 result > 1 Then     'Code A1 ElseIf result < 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, since 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 moves 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 result were less than 1. If this were the case, 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. Note that 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

There are several ways to discuss what is evaluated in an If statement. Essentially, the code between the If and Then portion 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, although the code 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 statement should consider the failure of a given comparison as a reason to execute the code encapsulated by its condition. An example of this is shown in the next example:

  If Not result = 1 Then     'Code A1 End If 

It is therefore possible to compare two values and then take the resulting Boolean from this comparison and reevaluate the result. In this case, the result is only reversed, but the If statement supports more complex comparisons using statements such as And and Or. These statements enable you to create a complex condition based on several comparisons, as shown here:

  If Not result = 1 Or result < 0 And value < 0 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 will occur.

There is a 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 of writing 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 result = 1) Or result < 0) And (value < 0) Then If (Not result = 1) Or (result < 0 And value < 0) Then If Not ((result = 1 Or result < 0) And value < 0) 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 illustrate 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, if the desired behavior were to execute this expensive call only when necessary, then you might want to use one of the shortcut comparison operators.

Since you know that for an And statement both sides of the If statement must be true, there are times when knowing that the first condition is false 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 this case, the AndAlso and OrElse statements allow for performance optimization.

  If ((Not result = 1) Or result < 0) AndAlso (MyMethod() = "Success") Then If Not result = 1 OrElse (result < 0 And MyMethod() = "Success") Then 

In each of the preceding cases, there are situations where the code associated with MyMethod won’t be evaluated. 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. This introduces yet another pair of conditional elements: the Is and IsNot conditionals.

Using Is 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 as a developer first determined whether the value was null, followed by a separate If statement to determine whether the value was valid. 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 code in the preceding example would fail on the first comparison because mystring has only been initialized to Nothing, meaning that by definition it doesn’t have a length. Note also that the second condition will fail because we 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, there is a scenario in which you may have a simple condition that needs to be tested repeatedly. For example, let’s say 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 myIntegerValue     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 myIntegerValue. 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 will execute the code represented by C3. 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 

For Each and For Next

The For structure in Visual Basic is the primary way of managing loops. It actually has two different formats. A standard For Next statement enables you to set a loop control variable that can be incremented by the For statement and custom exit criteria from your loop. Alternatively, if you are working with a known collection, then it is possible to use a For Each loop to automatically loop through all of the items in that collection:

  For control As Integer = 1 To 10 Step 2     MyGrid.Rows(control).Visible = False Next 

The For Next structure is most commonly set up to traverse an array or similar construct (for example, a dataset). The control variable control in the preceding example must be numeric. The value can be incremented from a starting value to an ending value, which are 1 and 10, respectively, in this example. Finally, it is possible to accept the default increment of 1; or, if desired, you can add a “Step” qualifier to your command and update the control value by a value other than 1. Best practices call for your control value to be an integer. Note that the preceding example hides every other line in the grid starting with the second line, since like all .NET collections, the collection starts at 0.

In addition, Visual Basic provides two additional commands that can be used within the For loop’s block to enhance performance. The first is Exit For; and as you might expect, this statement causes the loop to end and not continue to the end of the processing. The other is Continue, which tells the loop that you are finished executing code with the current control value and to move to increment the value and reenter the loop for its next iteration:

  For control As Integer = 1 To 10 Step 2     If MyGrid.Rows.Count < control Then Exit For     If control = 5 Then Continue For     MyGrid.Rows(control).Visible = False Next 

Each of these keywords has been used in the preceding example. Note how each uses a format of the If Then structure that places the command on the same line as the If statement so that no End If statement is required. This loop exits if the control value is larger than the number of rows defined for the grid. Additionally, if the control indicates you are looking at the sixth row (index of five), then this row is not to be hidden, so the code does not process the next line to hide that row.

However, those examples demonstrate that in most cases, since your loop is going to process a known collection, Visual Basic provides a command that encapsulates the management of the loop control variable. The For Each structure automates the counting process and enables you to quickly assign the current item from the collection, so that you can act on it in your code. It is a common way to process all of the rows in a data set or most any other collection, and all of the loop control elements such as Continue and Exit are still available.

  For Each Row As DataGridViewRow In MyGrid.Rows     'Code A1 Next 

While, Do While, and Do Until

In addition to the For loop, Visual Basic includes the While and Do loops, with two different versions of the Do loop. The first is the Do While loop. With a Do While loop, your code starts by checking for a condition; and as long as that condition is true, it executes the code contained in the Do loop. Optionally, instead of starting the loop by checking the While condition, the code can enter the loop and then check the condition at the end of the loop. The Do Until loop is similar to the Do While loop:

  Do While MyGrid.Rows.Count > 0      'Code A1      System.Threading.Thread.Sleep(500) Loop 

The Do Until differs from the Do While only in that, by convention, the condition for a Do-Until is placed after the code block, thus requiring the code in the Do block to execute once before the condition is checked. It bears repeating, however, that a Do Until block can place the Until condition with the Do statement instead of with the Loop statement, and a Do While block can similarly have its condition at the end of the loop:

  Do     'Code A1     System.Threading.Thread.Sleep(500) Loop Until (MyGrid.Rows.Count = 0) 

In both cases, instead of basing the loop around an array of items or a fixed number of iterations, the loop is instead instructed to continue perpetually until a condition is met. A good use for these loops involves tasks that need to repeat for as long as your application is running. Similar to the For loop, there are Exit Do and Continue commands that end the loop or move to the next iteration, respectively. Note that parentheses are allowed but are not required for both the While and the Until conditional expression.

The other format for creating a loop is to omit the Do statement and just create a While loop. The While loop works similarly to the Do While loop. The differences are as follows: First, the While loop’s end point is an End While statement. Second, the condition must be at the start of the loop with the While statement. The final difference is that the While loop has an Exit While statement instead of Exit Do, although the behavior is the same. An example is shown here:

  While MyGrid.Rows.Count > 0    'Code A1     System.Threading.Thread.Sleep(500) End While 

The best way to explain the use of these potentially endless loops is to illustrate how you might use one. For example, if you were writing an e-mail program, you might want to check the user’s mailbox on the server every 20 seconds. You would create a Do While or Do Until loop that would contain the code to open a network connection and check the server for any new mail messages to download. You would continue this process until either the application was closed or you were unable to connect to the server. If unable to connect to the server, you would then alert the user and probably start a new loop that would look for network connectivity on a regular basis. One warning with this type of loop: If you are going to monitor a system’s status, always include a call to Thread.Sleep() so that the loop only executes a single iteration within a given time frame, to avoid consuming too much processor time.




Professional VB 2005 with. NET 3. 0
Professional VB 2005 with .NET 3.0 (Programmer to Programmer)
ISBN: 0470124709
EAN: 2147483647
Year: 2004
Pages: 267

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