Section A.1. Language Changes for VB.NET

   

A.1 Language Changes for VB.NET

In this section, we outline the changes made to the Visual Basic language from Version 6 to Visual Basic .NET. These language changes were made to bring VB under the umbrella of the .NET Framework and allow a Common Language Runtime for all languages in Visual Studio .NET. In some sense, the changes made to the VB language were to bring the language component of VB (as opposed to the IDE component) more in line with the C# language (which is a derivative of C and C++).

Since we assume in this chapter that you are familiar with VB 6, we will not necessarily discuss how VB 6 handles a given language feature, unless the contrast is specifically helpful. You can assume that if a VB.NET language feature is described in this chapter, there has been a change in its behavior since VB 6.

A.1.1 Data Types

There have been fundamental changes to data types in VB.NET, which we outline in this section. The most important change is that all of the languages under the .NET umbrella (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). We say subset because VB.NET does not implement all of these data types. In any case, each data type in the BCL is implemented either as a class or as a structure (which is similar to a class) and, as such, has members . The VB.NET data types are wrappers for the corresponding BCL data type. While this need not concern the VB programmer, it can be used in some cases to expose a bit more functionality from a data type. For more on data types, see Chapter 3.

Now let us consider the specifics.

A.1.1.1 Strings

As you may know, in VB 6, strings were implemented as a data type known as the BSTR. 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 String class, which is part of the .NET Framework's System namespace.

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

 Dim Name As String * 30 

Note, though, that strings in VB.NET are immutable. That is, although you do not have to declare a string's length in advance, once a value is assigned to a string, its length cannot change. If you change that string, the .NET Common Language Runtime actually gives you a reference to a new String object. (For more on this, see Chapter 3.)

A.1.1.2 Integer/Long data type changes

VB.NET defines the following signed-integer data types:

Short

The 16-bit integer data type. It is the same as the Int16 data type in the Base Class Library.

Integer

The 32-bit integer data type. It is the same as the Int32 data type in the Base Class Library.

Long

The 64-bit integer data type. It is the same as the Int64 data type in the Base Class Library.

Thus, with respect to the changes from VB 6 to VB.NET, we can say:

  • The VB 6 Integer data type has become the VB.NET Short data type.

  • The VB 6 Long data type has become the VB.NET Integer data type.

A.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 , meaning that it can hold data of any other data type. According to the documentation, all of the functionality of the Variant data type is supplied by the Object data type.

We cannot resist the temptation to add that there are several penalties associated with using a universal data type, including poor performance and poor program readability. Thus, while VB.NET still provides this opportunity through the Object data type, its use is not recommended whenever it can be avoided.

The VarType function, which was used in VB 6 to determine the type of data stored in a variant variable (that is, the variant's data subtype ), now reports the data subtype of the Object type instead. In addition, the TypeName function, which can be used to return a string that indicates the data type of a variable of type Object, is still supported.

A.1.1.4 Other data type changes

Here are some additional changes in data types:

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

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

  • In VB 6, a date is stored in a Double format using four bytes. In VB.NET, the Date data type is an 8-byte integer data type whose range of values is from January 1, 1 to December 31, 9999.

A.1.2 Variables and Their Declaration

The changes in variable declarations and related issues are described here.

A.1.2.1 Variable declaration

The syntax used to declare variables has changed for VB.NET, making it more flexible. Indeed, these are long awaited changes.

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 x As Long,   i, j, k   As Integer, s As String 

the variables i , j , and k have type Integer. (In VB 6, the variables i and j would have type Variant, and only the variable k would have type Integer.)

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

A.1.2.2 Variable initialization

VB.NET permits the initialization of variables in the same line as their declaration (at long last). Thus, we may write:

 Dim   x   As Integer = 5 

to declare an Integer variable and initialize its value to 5. Similarly, we can declare and initialize more than one variable on a single line:

 Dim   x   As Integer = 6,   y   As Integer = 9 
A.1.2.3 Variable scope changes

In VB 6, a variable that is declared anywhere in a procedure has procedure scope ; that is, 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 , or Next statement), then the variable has block- level scope ; that is, it is visible only within that block.

For example, consider the following VB.NET code:

 Sub Test(  )    If x <> 0 Then       Dim rec As Integer       rec = 1/x    End If    MsgBox CStr(rec) End Sub 

In this code, the variable rec is not recognized outside the block in which it is defined, so the final statement will produce an error.

It is important to note that 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 the code block was executed.

A.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 whose lower bound was not explicitly specified. In VB.NET, the lower bound of every array dimension is 0 and cannot be changed. The following examples show how to declare a one-dimensional array, with or without an explicit size and with or without 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} 

Note that in the declaration:

 Dim ArrayName(X) As ArrayType 

the number X is the upper bound of the array. Thus, the array has size X+1.

Multidimensional arrays are declared similarly. For instance, the following example declares and initializes a two-dimensional array:

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

and the following code displays the contents of the array:

 Debug.Write(X(0, 0)) Debug.Write(X(0, 1)) Debug.Writeline(X(0, 2)) Debug.Write(X(1, 0)) Debug.Write(X(1, 1)) Debug.Write(X(1, 2)) 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. Note, however, that the number of dimensions of an array cannot be changed.

Moreover, unlike VB 6, the ReDim statement cannot be used for array declaration, but only for array resizing. All arrays must be declared initially using a Dim (or equivalent) statement.

A.1.2.5 Structure/ user -defined type declarations

In VB 6, a structure or user-defined type is declared using the Type ... End Type structure.

In VB.NET, the Type statement isn't supported. Structures are declared using the Structure ... End Structure construct. Also, each member of the 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 

is defined in VB.NET as:

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

Actually, the VB.NET Structure type is far more reaching than its VB 6 user- defined type predecessor. Indeed, structures have many properties in common with classes; for instance, structures can have members (properties and methods ). We discuss structures in detail in Chapter 3.

A.1.3 Boolean and Bitwise Operators

Eqv and Imp , two infrequently used Boolean and bitwise operators that are present in VB 6, have been removed from VB.NET.

In VB 6, Eqv is the logical equivalence operator. As a Boolean operator, it returns True if both expressions 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 if both 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 equals comparison operator for logical operations. However, for bitwise operations, you'll have to resort to a bit-by-bit comparison, as the following code fragment shows:

 Public Function BitwiseEqv(x1 As Byte, X2 As Byte) _                            As Long   Dim b1, b2, bRet As Byte Dim iCtr as Integer For iCtr = 0 to len(x1) * 8 - 1    b1 = x1 and 2^iCtr    b2 = x2 and 2^iCtr    if b1 = b2 then bRet += 2^iCtr next BitwiseEqv = bRet End Function 

In VB 6, Imp is the logical implication operator. As a Boolean operator, it returns True unless its first expression is True while the second is False . As a bitwise operator, it returns 1 unless the bit in the first expression is 1 while the bit in the second expression is 0. In VB.NET, Imp can be replaced with a combination of the Not and Or operators for logical operations. For example, the code fragment:

 bResult = (Not bFlag1) Or bFlag2 

is equivalent to the VB 6 statement:

 bResult = bFlag1 Imp bFlag2 

For bitwise operations, a bit-by-bit comparison is again necessary, as the following code fragment shows:

 Public Function BitwiseImp(x1 As Byte, X2 As Byte) As Long Dim b1, b2, bRet As Byte Dim iCtr as Integer For iCtr = 0 to len(x1)*8 - 1    b1 = Not(x1) and 2^iCtr    b2 = x2 and 2^iCtr    if b1 Or b2 then        bRet += 2^iCtr    end If next BitwiseImp = bRet End Function 

Unlike previous versions of Visual Basic, most programming languages use short-circuiting when evaluating If statements. That is, if an If statement contains multiple subexpressions joined by Boolean operators, expressions are evaluated from left to right, and once the truth or falsity of the expression is known, the remaining subexpressions are not evaluated. This applies in particular to subexpressions joined by a logical And (the expression is necessarily False if the first subexpression is False ) and by a logical Or (the expression is necessarily True if the first subexpression is True ).

VB.NET now supports short circuiting through the use of the AndAlso and OrElse logical operators. If these operators are used, once the value of an expression is known, any further subexpressions will not be evaluated. 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 has introduced new operators to support short circuiting, rather than simply modify 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). This isn't the case, however, if an expression calls a function that modifies the value of a variable. 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 

Here, we can never be certain whether the second call to the Increment function will occur and whether the value of y will be incremented. In this case, it's preferable to avoid short-circuiting with AndAlso in favor of the And operator.

A.1.4 Changes Related to Procedures

VB.NET features a number of changes to the way in which procedures are defined and called, most of which tend to make the language more streamlined and consistent.

A.1.4.1 Calling a procedure

In VB 6, parentheses are required around arguments when making function calls. When calling a subroutine, parentheses are required when using the Call statement and proscribed when not using the Call statement.

In VB.NET, parentheses are always required around a nonempty argument list in any procedure call ” function or subroutine. (In subroutine calls, the Call statement is optional.) When calling a parameterless procedure, empty parentheses are optional.

A.1.4.2 Default method of passing arguments

In VB 6, if the parameters to a function or subroutine were not explicitly prefaced with the ByVal or ByRef keywords, arguments were passed to that routine by reference, and modifications made to the argument in the function or subroutine were reflected in the variable's value once control returned to the calling routine. In VB.NET, on the other hand, if the ByRef or ByVal keyword is not used in 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 program.

A.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 can be used to determine whether the parameter is present.

In VB.NET, an optional parameter must declare a default value, which is passed to the procedure if the calling program does not supply an argument for that parameter. The IsMissing function is not supported. The following example shows an optional parameter declaration:

 Sub Calculate(Optional ByVal Switch As Boolean = False) 
A.1.4.4 Return statement

In VB.NET, the Return statement is used to return control to the calling program from a function or subroutine. The GoSub statement is not supported. Note that the Return statement is used to return a value from a function.

The following function illustrates the Return statement:

 Public Function Test(  ) As Integer     If MsgBox("Return", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then         Return 0     Else         MsgBox("Continue")         Return 1     End If End Function 
A.1.4.5 Passing property parameters in procedures

Consider passing a property to a procedure by reference, as in:

 Sub ShrinkByHalf(ByRef lSize As Long)    lSize = CLng(lSize/2) End Sub Call ShrinkByHalf(Text1.Height) 

In VB 6, when passing the value of a property by reference, the property is not updated. In other words, passing a property by reference is equivalent to passing it by value. Hence, in the previous example, the property Text1.Height will not be changed.

In VB.NET, passing a property by reference does update the property, so in this case, the Text1.Height property will be changed. Note, however, that the value of the property is not changed immediately, but rather when the called procedure returns.

A.1.4.6 ParamArray parameters

In VB 6, if the ParamArray keyword is used on the last parameter of a procedure declaration, the parameter can accept an array of Variant parameters. In addition, ParamAarray parameters are always passed by reference.

In VB.NET, ParamArray parameters are always passed by value, and the parameters in the array may be of any data type.

A.1.5 Miscellaneous Language Changes

VB.NET includes several miscellaneous changes that include the format of line numbers , the lack of support for the GoTo and GoSub statements, and the replacement of the Wend keyword by End While .

A.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, line labels, which were used in particular for error handling by the On Error GoTo statement, had to be followed immediately by a colon, but line numbers did not.

A.1.5.2 On GoTo

The On ... GoSub and On ... GoTo constructs are not supported. However, VB.NET still supports the On Error GoTo statement.

A.1.5.3 While

The While ... Wend construction loops through code while a specified condition is True . VB.NET retains that construction, but replaces the Wend keyword with the End While statement. The Wend keyword is not supported.

A.1.5.4 GoSub and Return statements

In VB.NET, the GoSub statement is not supported.

As remarked earlier, in VB.NET, the Return statement is used to return control to the calling program from a function or subroutine. The VB 6 Exit Sub and Exit Function statements continue to be supported in VB.NET; however, the advantage of the Return statement is that it allows you to specify the function's return value as an argument to the Return statement.

   


VB.Net Language in a Nutshell
VB.NET Language in a Nutshell
ISBN: B00006L54Q
EAN: N/A
Year: 2002
Pages: 503

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