Miscellaneous Changes

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.

New Shortcut Operators

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").

+=Shorthand for adds a value and assigns the resultX += 2 (X holds 8)
[ms]=Shorthand for subtracts a value and assigns the resultX [ms]= 3 (X holds 3)
*=Shorthand for multiplies a value and assigns the resultX *= 6 (X holds 36)
/=Shorthand for divides by a value and assigns the resultX /= 2 (X holds 3)
&=Shorthand for combines with a string and assigns the resultS &= ", John" (S holds “Hello World, John”)

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.

No More Default Properties

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.

SHOP TALK: BEING EXPLICIT

As you read through the descriptions for each of the changes between Visual Basic 6.0 and Visual Basic .NET, you should start to notice a common theme. For many of these issues, what is changing is the default behavior, what happens when you haven't explicitly specified what you wanted. Consider the case of variables without a datatype, you are essentially stating that you don't know what you are going to use that variable for and leaving it up to the compiler to figure out what to do. There certainly are times when you need a variable that can hold anything (a Variant in Visual Basic 6.0 and an Object in Visual Basic .NET), but in most cases where I have seen undeclared variables or variables declared without datatypes, the use of the variable was very well known, but the programmer just didn't bother to specify a datatype. To save a bit of typing, the code of your project became a little harder to understand and now harder to upgrade.

The same goes for default properties, although you always knew you were interested in the .Text property of that TextBox, some programmers skipped it because they could and everything ended up working. Well, once again, a few characters of extra typing have been saved in return for more confusing source code. I have often been bugged by other programmers when they see me using .Text, ByRef/ByVal and other unnecessary bits of code in my Visual Basic 6.0 projects, but I have always tried to err on the side of being fully explicit. The less insider information a person needs about your code and the version of the compiler you were using when it was written the better.

Whenever possible, and you don't have a choice in most places in Visual Basic .NET, be explicit in your coding (and your documentation) and you will be thankful in the long run.


New Loop Syntax

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.

Listing 2.15. Declaring Control Variables Outside of the Loop
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.

Listing 2.16. Declaring the Control Variable as Part of the Loop Statement
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.

Listing 2.17. For Each Loops Benefit from the Same New Feature
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.

Listing 2.18. Control Variables Declared Outside of the Loop Are Available After the Loop has Completed
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.

Listing 2.19. Declaring Your Control Variable as Part of the Loop Means it Is Scoped to Just That Loop
For idx As Integer = 0 To 10
    'do nothing
Next
MsgBox(idx)
					

New BitShift Operators

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.

Listing 2.20. BitShifting Manipulates Integers by Moving their Underlying Bits a Specified Number of Positions to the Left or Right
Private Sub btnBitShift_Click( _
    ByVal sender As System.Object, _
    ByVal e As System.EventArgs) _
        Handles btnBitShift.Click
    '&HFF = the hex value FF, which equals 255, and
    '1111 1111 in binary
    Dim numberToBeShifted As Integer = &HFF

    numberToBeShifted = numberToBeShifted << 4
    numberToBeShifted >>= 2
    MsgBox(numberToBeShifted)
End Sub

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.

New Short-Circuiting Conditionals

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.

Listing 2.21. Short-Circuiting Promotes the Most Efficient Processing of Boolean Expressions by Skipping Unnecessary Expression Evaluations
Private Sub Button1_Click( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs) _
            Handles Button1.Click
    If Test("Left") AndAlso Test("Right") Then
        'do something
    End If
End Sub

Function Test(ByVal sInput As String) As Boolean
    Debug.WriteLine(sInput)
    Test = False
End Function
					

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 ANDOUTPUT WITH ANDALSO
FalseLeft RightLeft
TrueLeft RightLeft Right

VALUE RETURNED BY TEST()OUTPUT WITH OROUTPUT WITH ORELSE
FalseLeft RightLeft Right
TrueLeft RightLeft

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.

Class, Sub, and Function Changes

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.

Files No Longer Define Classes, Forms, or Modules

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.

Listing 2.22. A Single .VB File Can Contain Multiple Classes, Modules, and/or Forms by Using the Class…End Class and Module…End Module Keywords
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.

ByVal by Default

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.

Listing 2.23. The Same Code Can Produce Different Results Depending on the Version of Visual Basic Used
'VB6 Code
Private Sub Command1_Click()
    Dim myInteger As Integer
    myInteger = 5
    TestByVal myInteger
    MsgBox myInteger
End Sub

Private Sub TestByVal(inty As Integer)
   inty = inty * 2
End Sub
'VB.NET Code
Private Sub Button1_Click( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs) _
        Handles Button1.Click
    Dim myInteger As Integer = 5
    TestByVal(myInteger)
    MsgBox(myInteger)
End Sub

Private Sub TestByVal(int As Integer)
    int = int * 2
End Sub
						

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.

Parentheses Are Now Required

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.

Listing 2.24. Parameter Arguments
'VB6
MsgBox "MsgBoxPrompt", vbCritical, "MsgBoxTitle"

'VB.NET
MsgBox("MsgBoxPrompt", vbCritical, "MsgBoxTitle")
						

Returning a Value from a Function

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.

Listing 2.25. Visual Basic .NET Supports the Return Statement to End a Function and Specify a Return Value
Function ComputeSalesTax(ByVal amount As Double, _
    ByVal tax As Single) As Double
    'could use ComputeSalesTax = amount * tax
    Return amount * tax
End Function
						

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

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