For the most part, Visual Basic 6.0's operators and statements have made it into Visual Basic .NET without any changes, but a few have been altered or removed completely. A brief list of the removed language elements includes Imp, Eqv, GoSub, LSet, VarPtr, ObjPtr, StrPtr, AscB, ChrB, and MidB. If none of those elements sounds familiar, it is not surprising as they are all infrequently used. In addition to those elements that have been removed, several new language features have been added including new shortcut operators, new loop syntax, new bit shift operators and new short-circuiting versions of the standard And/Or Boolean operators.
A few other changes have occurred in the syntax for defining classes, calling procedures, specifying ByRef vs. ByVal parameters, and setting the return value of a function, all of which are covered in the “Class, Sub, and Function Changes” section later in the chapter.
Visual Basic .NET introduces a new syntax for performing some simple mathematical operations, essentially shortcuts for the normal method of performing these operations. Each of the new operators is shown in the following table (the sample column assumes that X is equal to six and S is equal to "Hello World").
In each case, the result is the same as using the regular syntax (x += 2 is exactly the same as x = x + 2), but the shorter form appeals to many programmers, especially those who come from a C++ background. Although you might have also seen the ++ or — syntax (which increments or decrements a variable by one) in another language, that syntax has not been added to the Visual Basic .NET language.
In Visual Basic 6.0 controls and classes could have default properties, which would be assumed if no property name was specified. These default properties allowed for quite a few code shortcuts, including omitting the Text property when working with a TextBox control, but they are no longer available in Visual Basic .NET.
For and For Each loops each require special variables that represent the index of the loop in the case of the For loop or are populated with an element of an expression in the case of the For Each loop. In earlier versions of Visual Basic (and even in the original 2002 release of Visual Basic .NET), these control variables had to be declared before they could be used in the loop statement (assuming declaration of variable was required due to the Option Explicit statement). An example of declaring and then using a control variable in both the For and For Each loops is shown in Listing 2.15. Note that Debug.WriteLine (shown in the same listing) is the VB .NET equivalent of the Visual Basic 6 method Debug.Print (which has been removed from the language), and it will output values to the Output window of Visual Studio .NET.
Dim idx As Integer For idx = 0 To 10 Debug.WriteLine(idx) Next Dim driveLetter As String For Each driveLetter In Environment.GetLogicalDrives() Debug.WriteLine(driveLetter) Next |
Now, with the changes in the Visual Basic .NET 2003 release, you can declare your control variable as part of the loop statement. An example of the new syntax is shown in Listing 2.16 for a simple For loop with an integer control variable that is incremented from 0 to 10.
For idx As Integer = 0 To 10 Debug.WriteLine(idx) Next |
The syntax for the For Each statement is the same (and is shown in listing 2.17), although the type for a For loop must be a primitive numeric (Byte, Short, Integer, Long, Decimal, Single, or Double). In the case of For Each loop, the type is dependent on the particular expression being enumerated through.
For Each driveLetter As String _ In Environment.GetLogicalDrives() Debug.WriteLine(driveLetter) Next |
This new loop variable, if defined within the For/For Each statement, is scoped to the loop block; meaning that it is unavailable outside of that section of code. The restricted scope of this new variable means that if you need access to the loop variable outside of the loop itself, you will need to use the pre-existing method; defining your variable prior to using it in the For or For Each statement. For example, Listing 2.18 compiles successfully and displays a value of 11.
Dim idx As Integer For idx = 0 To 10 'do nothing Next MsgBox(idx) |
If the variable had been defined as part of the For statement, it would be out of scope once the For loop ends. The code in Listing 2.19 will not even compile, as it results in a "Name 'idx' is not declared." error on the last line.
For idx As Integer = 0 To 10 'do nothing Next MsgBox(idx) |
BitShifting is the modification of a number by moving all of its bits a specified number of positions to the left or right. Bits that fall outside of the size of the original value (on either the high or low sides of the binary value) are discarded. The code sample shown in Listing 2.20 illustrates shifting a binary value four positions to the left and then two to the right. Note the numberToBeShifted >>= 2 on line 10; this is a shortcut operator for numberToBeShifted = numberToBeShifted >> 2, and one exists for left shifting as well.
Although BitShifting has been a commonly used technique in computer mathematics for a very long time, Visual Basic has never had direct support for this operation before the release of Visual Basic .NET 2003. Before these two operators were available, you could achieve the same effect as a BitShift by multiplying or dividing your value by a power of 2 (the exponent represents the number of positions to shift), but an actual BitShift such as these new operators provide is faster.
Similar to an election outcome in the United States, the result of a Boolean expression is often known before the complete expression has been evaluated. Consider this Boolean expression: (X > 1) AND (X < 10). If X is one, as soon as you evaluate the left side of the expression (returning False), you know that the right side is irrelevant. Due to the nature of the AND operator, there is no need to evaluate the other side. The entire expression will be False, no matter what value is returned on the other side. This is something that a human would do without much thought when evaluating Boolean expressions, but it is not always so clear for the computer.
The behavior that we expect, not evaluating the unnecessary portion of an expression, is called short-circuiting, but neither Visual Basic 6.0 nor Visual Basic .NET work this way by default. To make Visual Basic .NET short-circuit a Boolean expression, you need to use alternative forms of the AND and OR operators, ANDALSO and ORELSE. You do not need to just trust that it behaves in this fashion though; some simple test code (see Listing 2.21) can be used to see exactly what happens.
If the Test() function returns False, as it does in Listing 2.21, you know what the overall expression will return simply by evaluating the left side. Running the code in Listing 2.21 will produce only one line of debug output, in this case, "Left". If Test() returns True, both sides need to be executed, and the program will output both "Left" and "Right". To test the behavior of Boolean operators, try both True and False for the return value of Test and switch between AndAlso/And/Or/OrElse in the If statement to see what results you get.
VALUE RETURNED BY TEST() | OUTPUT WITH AND | OUTPUT WITH ANDALSO |
---|---|---|
False | Left Right | Left |
True | Left Right | Left Right |
VALUE RETURNED BY TEST() | OUTPUT WITH OR | OUTPUT WITH ORELSE |
---|---|---|
False | Left Right | Left Right |
True | Left Right | Left |
In this sample code, it wouldn't be a terrible hit to the program's performance if both sides of the expression were evaluated every time the If statement was executed, but if the function(s) in question were more complicated and more time consuming, using a short-circuiting operator could really help performance. For maximum benefit, you should structure your expressions so that the most complicated portions appear to the right of the short-circuiting operator.
There have been a few changes to how you create classes, define procedures, and set function return values in Visual Basic .NET, covered in the following sections.
Classes , modules, and forms are no longer file based; now they are based on statements in the code file that mark the beginning and end of the particular item in question. This means that a single code file can contain any number of classes, forms, or modules, as illustrated in Listing 2.22.
Public Class Class1 Public Sub DoSomething(ByVal howManyTimes As Integer) End Sub End Class Module Module1 Sub Main() Dim x As New Class1 x.DoSomething(5) End Sub End Module |
Although it is now possible to include more than one class in a single .vb file, it is generally considered best to stick with only one class per file.
Parameters in procedure declarations default to ByVal (passed by value), whereas they defaulted to ByRef (pass by reference) in Visual Basic 6.0 and earlier. The best way to handle this change is to always explicitly state ByRef or ByVal for each of the parameters in your procedure. Listing 2.23 shows two pieces of code, one in Visual Basic 6.0 and one in Visual Basic .NET. They appear very similar but behave differently due to this change.
The Visual Basic 6 code displays a result of 10, whereas the Visual Basic .NET code would display 5. Note that it would be difficult to even produce the Visual Basic .NET code from Listing 2.23 in Visual Studio .NET. Visual Studio .NET automatically adds the ByVal next to your variable name, when you write code like the procedure declaration shown on Line 11 of the VB .NET code.
When invoking a procedure in Visual Basic 6.0 and earlier, parentheses were required around the arguments when calling functions, but were not allowed when calling Sub procedures unless you used the Call statement in front of your call to the Sub procedure. In Visual Basic .NET, parentheses are required (and will be automatically added by Visual Studio .NET) around the arguments for both Sub and Function calls. Listing 2.24 demonstrates the difference, showing you a valid MsgBox call in both VB6 and VB.NET.
'VB6 MsgBox "MsgBoxPrompt", vbCritical, "MsgBoxTitle" 'VB.NET MsgBox("MsgBoxPrompt", vbCritical, "MsgBoxTitle") |
To return the result from a function in Visual Basic 6.0, you assigned the result to the function name, and that value would be returned to the calling program when the function exited. This syntax is still available in Visual Basic .NET, but now you can alternatively use a Return statement to send back the result of the function and exit the function all at the same time. Listing 2.25 provides an illustration of the Return statement in action.
Function ComputeSalesTax(ByVal amount As Double, _ ByVal tax As Single) As Double 'could use ComputeSalesTax = amount * tax Return amount * tax End Function |
3.15.34.161