Section D.1. Language Changes in VB.NET 2002


D.1. Language Changes in VB.NET 2002

This section outlines the changes made to the Visual Basic language from Version 6 to Visual Basic .NET 2002. These language changes were made to bring VB under the umbrella of the .NET Framework and to provide VB access to the Common Language Runtime shared by all languages in the Visual Studio .NET family of languages.

D.1.1. Data Types

There have been fundamental changes to data types in the transition to VB.NET. The most important change is that all .NET-compliant languages (including VB, C#, and Managed C++) now implement a subset of a common set of data types, defined in the .NET Framework's Base Class Library (BCL); specific languages, including VB.NET 2002, do not implement all available BCL data types. Each data type in the BCL is implemented either as a class or as a structure and, as such, has members. The VB.NET data types are wrappers for the corresponding BCL data types. Because of this, any feature of the .NET Framework that uses a specific BCL data type will work seamlessly with the equivalent VB.NET data type. For more discussion on data types, see Chapter 4.

D.1.1.1. Strings

In VB 6, strings were implemented as BSTRs ("B-Strings"). A BSTR is a pointer to a character array that is preceded by a 4-byte Long specifying the length of the array. In VB.NET, strings are implemented as objects of the System.String class.

One consequence of this reimplementation of strings is that VB.NET does not support fixed-length strings, as did VB 6. Thus, the following code is illegal:

     Dim sName As String * 30 

Strings in .NET are immutable. Once you assign a value to a string, neither its length nor its content changes. If you change a string, the .NET Common Language Runtime actually gives you a reference to a new String object. (For more on this, see Chapter 4.)

D.1.1.2. Integer/Long data-type changes

Visual Basic .NET 2002 defines the following signed-integer data types:


Short

A 16-bit integer data type, based on the System.Int16 data type.


Integer

A 32-bit integer data type, based on the System.Int32 data type.


Long

A 64-bit integer data type, based on the System.Int64 data type.

This means that in the transition from VB 6 to VB.NET:

  • The VB 6 Integer data type became the VB.NET Short data type.

  • The VB 6 Long data type became the VB.NET Integer data type.

  • The VB.NET Long data type has no direct equivalent in VB 6.

D.1.1.3. Variant data type

VB.NET does not support the Variant data type. The Object data type is VB.NET's universal data type; it can hold data of any other data type. Although its use is somewhat different from the Variant data type, both data types provide a general way to refer to a variety of data.

There are several penalties associated with using a universal data type, including poor performance and poor program readability. While VB.NET still provides this opportunity through the Object data type, its use is not recommended simply to avoid the clear categorization of your data values.

The VarType function, which was used in VB 6 to determine the type of data stored in a Variant variable (that is, it returned the Variant's data subtype), now reports the true data type of the Object instance instead. VB.NET still supports the TypeName function, which is used to return the name of the true data type of an Object variable.

D.1.1.4. Other data-type changes

Here are some additional changes in data types:

  • The Deftype statements (DefBool, DefByte, etc.), which were used to define the default data type for variables with names that began with particular letters of the alphabet, are not supported in VB.NET.

  • The Currency data type is not supported in VB.NET. However, VB.NET's Decimal data type can handle more digits on both sides of the decimal point than did the Currency data type, and it is a superior replacement. The VB.NET Decimal data type is a true data type; VB 6's Currency data type was a Variant subtype, and a variable could be cast as a Decimal in VB 6 only by calling the CDec conversion function.

  • In VB 6, dates and times were stored in a Double format using four bytes. In VB.NET, the Date data type is an 8-byte integral data type with a range of values that is from January 1, 1 to December 31, 9999 in the Gregorian calendar.

D.1.2. Variables and Their Declaration

Visual Basic .NET 2002 introduced several changes related to variable use.

D.1.2.1. Variable declaration

The syntax used to declare variables changed with VB.NET, making it more flexible. In VB.NET, when multiple variables are declared on the same line, if a variable is not declared with a type explicitly, then its type is that of the next variable with an explicit type declaration. Thus, in the line:

     Dim first As Long, second, third, fourth As Integer 

the variables second, third, and fourth are of type Integer. Using this same statement in VB 6 would have defined second and third as type Variant, and only the variable fourth would have been an Integer.

When declaring external procedures using the Declare statement, VB.NET does not support the As Any type declaration clause. All parameters must have a specific type declaration.

D.1.2.2. Variable initialization

VB.NET permits the initialization of variables on the same line as their declaration. The statement:

     Dim x As Integer = 5 

declares an Integer variable x and initializes its value to 5. More than one variable declaration and assignment may appear on a single line:

     Dim x As Integer = 6, y As Integer = 9 

D.1.2.3. Variable scope changes

In VB 6, a variable that is declared anywhere in a procedure has procedure scope; the variable is visible to all code in the procedure. In VB.NET, if a variable is defined inside a code block (a set of statements that is terminated by an End..., Loop, Next, or similar block closing keyword), then the variable has block-level scope; it is visible only within that block. For example, consider the following VB.NET code:

     Public Sub Test(sourceValue As Integer)        If (sourceValue <> 0) Then           Dim inverseResult As Integer           inverseResult = 1 / sourceValue        End If        ' ----- The next line is invalid.        MsgBox(CStr(inverseResult))     End Sub 

In this code, the variable inverseResult is not recognized outside the block in which it is defined, so the final statement will produce a compile-time error.

The lifetime of a local variable is always that of the entire procedure, even if the variable's scope is block-level. This implies that if a block is entered more than once, a block-level variable will retain its value from the previous time through the code block.

D.1.2.4. Arrays and array declarations

VB 6 permitted you to define the lower bound of a specific array, as well as the default lower bound of arrays with a lower bound that was not explicitly specified. In VB.NET, the lower bound of every array dimension is zero and cannot be changed. The following examples show how to declare a one-dimensional array, with or without an explicit size and initialization:

     ' Implicit constructor: No initial size and no initialization     Dim days(  ) As Integer     ' Explicit constructor: No initial size and no initialization     Dim days(  ) As Integer = New Integer(  ) {}     ' Implicit constructor: Initial size but no initialization     Dim days(6) As Integer     ' Explicit constructor: Initial size but no initialization     Dim days(  ) As Integer = New Integer(6) {}     ' Implicit constructor: Initial size implied by initialization     Dim days(  ) As Integer = {1, 2, 3, 4, 5, 6, 7}     ' Explicit constructor: Initial size and initialization     Dim days(  ) As Integer = New Integer(6) {1, 2, 3, 4, 5, 6, 7} 

In the declaration:

     Dim arrayName(upperBound) As arrayType 

the number upperBound is the upper bound of the array. Thus, the array has size upperBound + 1, with elements 0 through upperBound.

Multidimensional arrays are declared similarly. The following example declares and initializes a two-dimensional array:

     Dim someData(,) As Integer = {{1, 2, 3}, {4, 5, 6}} 

The following code displays the contents of that array:

     Debug.Write(someData(0, 0))     Debug.Write(someData(0, 1))     Debug.WriteLine(someData(0, 2))     Debug.Write(someData(1, 0))     Debug.Write(someData(1, 1))     Debug.WriteLine(someData(1, 2))     ' ----- The output is:     123     456 

In VB.NET, all arrays are dynamic; there is no such thing as a fixed-size array. The declared size should be thought of simply as the initial size of the array, which is subject to change using the ReDim statement. The number of dimensions of an array cannot be changed.

The ReDim statement in VB.NET cannot be used for array declaration but only for array resizing, which differs from the functionality in VB 6. All arrays must be declared initially using the Dim (or equivalent) statement.

D.1.2.5. Structure/user-defined type declarations

In VB 6, a structure or user-defined type is declared using the Type...End Type syntax. In VB.NET, the Type statement isn't supported. Structures are declared using the Structure...End Structure construct. Each member of this structure must be assigned an access modifier, which can be Public, Protected, Friend, Protected Friend, or Private. (The Dim keyword is equivalent to Public in this context.)

For instance, the VB 6 user-defined type:

     Type RECT        Left As Long        Top As Long        Right As Long        Bottom As Long     End Type 

has the following equivalent VB.NET declaration:

     Structure RECT        Public Left As Integer        Public Top As Integer        Public Right As Integer        Public Bottom As Integer     End Structure 

VB.NET Structure types are far more reaching than their VB 6 user-defined type counterparts. Structures in .NET have many properties in common with classes, such as the presence of members (like properties and methods). Structures are discussed in detail in Chapter 4.

D.1.3. Logical and Bitwise Operators

Eqv and Imp, two infrequently used VB 6 logical and bitwise operators , have been removed from VB.NET.

In VB 6, Eqv is the equivalence operator. As a logical operator, it returns true if both operands are either TRue or False, but it returns False if one is true while the other is False. As a bitwise operator, it returns 1 for a given bit if both source bits are the same (that is, if both are 1 or both are 0), but it returns 0 if they are different. In VB.NET, Eqv can be replaced with the Equal To (=) comparison operator for logical operations. If you require the true bitwise result of the equivalence operation, use the following code.

     Public Function BitwiseEqv(ByVal x1 As Byte, ByVal x2 As Byte) As Byte        ' ----- Functional equivalent to the VB 6 'Eqv' keyword.        Dim bit1 As Byte        Dim bit2 As Byte        Dim result As Byte = 0        Dim counter as Integer        ' ----- Scan each of the eight bits.        For counter = 0 To 7           ' ----- Compare this specific bit.           bit1 = x1 And 2 ^ counter           bit2 = x2 And 2 ^ counter           If (bit1 = bit2) Then result += 2 ^ counter        Next counter        Return result     End Function 

In VB 6, Imp is the implication operator. As a logical operator, it returns TRue in all cases except when the first operand is TRue and the second is False. As a bitwise operator, it returns 1 in a bit position in all cases, except when that positional bit in the first operand is 1 and the same bit in the second operand is 0. In VB.NET, Imp can be replaced with a combination of the Not and Or operators for logical operations. For example, the statement:

     result = (Not flag1) Or flag2 

is equivalent to the VB 6 statement:

     result = flag1 Imp flag2 

For bitwise operations, a bit-by-bit comparison is again necessary. The following code implements the missing functionality.

     Public Function BitwiseImp(ByVal x1 As Byte, _           ByVal x2 As Byte) As Byte        ' ----- Functional equivalent to the VB 6 'Imp' keyword.        Dim bit1 As Byte        Dim bit2 As Byte        Dim result As Byte = 0        Dim counter As Integer        ' ----- Scan each of the eight bits.        For counter = 0 to 7           bit1 = Not(x1) And 2 ^ counter           bit2 = x2 And 2 ^ counter           If (bit1 Or bit2) Then result += 2 ^ counter        Next counter        Return result     End Function 

Many programming languages support short-circuiting, which allows the language to abort evaluation of a complex conditional expression early when it is already clear what the final logical result will be. As expressions are evaluated from left to right, once the eventual truth or falsity of the whole condition is known, the remaining expressions are skipped. For instance, if a condition includes two expressions joined with an "And" logical operator, short-circuiting ceases evaluation if the first expression evaluates to False, since the value of the second expression will not impact the final result.

Visual Basic 6 did not support short-circuiting, but VB.NET now supports it through the AndAlso and OrElse logical operators. If these operators are used (instead of the non-short-circuiting And and Or logical operators), the condition may exit early if warranted. For example, consider the statement:

     If (X AndAlso Y) Then 

If X is False, then Y is not evaluated, because the entire statement is False regardless of the truth value of Y.

VB.NET introduced new operators to support short-circuiting rather than simply modifying the behavior of And and Or, largely for reasons of compatibility. In most cases, short-circuiting has no effect on a program's execution other than an improvement in performance and an increase in robustness (expressions that are not evaluated cannot raise errors or consume CPU cycles). However, care must be taken when the second expression includes function calls. For example:

     If Increment(x) AndAlso Increment(y) Then        ' ----- Do something.     End If     ...     Private Function Increment(ByRef n As Integer) As Boolean        If (n < 10) Then           n += 1           Return True        Else           Return False        End If     End Function 

The original condition is somewhat ambiguous, since y will be incremented only sometimes. In such cases, it may be preferable to avoid short-circuiting with AndAlso in favor of the And operator.

D.1.4. Changes Related to Procedures

VB.NET includes several changes in the way that procedures are defined and called, with clearer and more consistent results.

D.1.4.1. Calling a procedure

In VB 6, parentheses are required around arguments when making function calls, but when calling subroutines, argument parentheses are only used with the Call keyword. In VB.NET, parentheses are always required around a non-empty argument list for any procedure callfunction or subroutine. (In subroutine calls, the Call statement is still optional.) When calling a procedure with no arguments, empty parentheses are optional.

D.1.4.2. Default method of passing arguments

In VB 6, if the parameters to a function or subroutine are not explicitly prefaced with the ByVal or ByRef keywords, arguments are passed to that routine by reference, and modifications made to the argument in the function or subroutine are reflected in the variable's value once control returns to the calling routine. In VB.NET, if the ByRef or ByVal keyword is not used with a parameter, the argument is passed to the routine by value, and modifications made to the argument in the function or subroutine are discarded once control returns to the calling routine.

D.1.4.3. Optional arguments

In VB 6, a procedure parameter can be declared as Optional without specifying a default value. For optional Variant parameters, the IsMissing function determines whether the parameter is present. In VB.NET, an optional parameter must declare a default value, which is passed to the routine if the calling code does not supply an argument. The IsMissing function is not supported. The following example shows an optional parameter declaration in VB.NET:

     Public Sub Calculate(Optional ByVal silent As Boolean = False) 

D.1.4.4. GoSub and Return statements

In VB 6, the GoSub and Return statements provide support for a subroutine-like block of code within a larger procedure. VB.NET no longer supports this construct. The GoSub statement has been removed from the language, and the Return statement is now used to exit a procedure immediately, with the option of setting the return value, as demonstrated in the following VB.NET code:

     Public Function SafeDivide(numerator As Decimal, _           denominator As Decimal) As Decimal        ' ----- Division with a check for divide-by-zero.        If (denominator = 0) Then           Return 0        Else           Return numerator / denominator        End If     End Function 

D.1.4.5. Passing Property parameters in procedures

In VB 6, properties passed as arguments to procedures were always passed by value, even if the procedure defined the argument as ByRef.

     Public Sub ShrinkToHalf(ByRef lSize As Long)        lSize = CLng(lSize / 2)     End Sub     ' ----- In some other routine...     Call ShrinkToHalf(Text1.Height) 

In VB 6, Text1.Height remains unaltered by the ShrinkToHalf routine. In VB.NET, properties passed to ByRef parameters will be updated to reflect any changes made within the procedure.

D.1.4.6. ParamArray parameters

In VB 6, a parameter marked with the ParamArray keyword only accepts arguments through the Variant data type, and the arguments are passed ByRef. In VB.NET, ParamArray parameters are always passed ByVal, and the parameters in the array may be of any data type.

D.1.5. Miscellaneous Language Changes

VB.NET includes several miscellaneous language changes that don't fit into other broad categories.

D.1.5.1. Line numbers

Visual Basic .NET requires that every line number be followed immediately by a colon (:). A statement can optionally follow the colon. In VB 6, nonnumeric line labels had to include a colon, but numeric line numbers did not.

D.1.5.2. On GoSub and On GoTo statements

The On...GoSub and On...GoTo value-based branching constructs are no longer supported. However, VB.NET still supports the On Error GoTo statement.

D.1.5.3. While statement

VB 6 included a While...Wend conditional loop construct. Although VB.NET retains this statement, it replaces the Wend keyword with the End While keyword pair.




Visual Basic 2005(c) In a Nutshell
Visual Basic 2005 in a Nutshell (In a Nutshell (OReilly))
ISBN: 059610152X
EAN: 2147483647
Year: 2004
Pages: 712

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