Changes to Variable Declaration

In addition to Option Strict, which can require variable declarations to include data types, Visual Basic .NET includes a few other changes in the way that variables are declared, the way arrays work, and how objects can be initialized and assigned. As mentioned earlier, the Def[Type] statements (DefInt, DefBool, DefStr, and so on) no longer exist in Visual Basic .NET; it is not possible to create a default data type definition based on the name of the variable.

Multiple Variables Declared Together

The first change is very minor, but has been a long time coming. In Visual Basic 6.0, if you declared multiple variables on a single line you could produce this very correct looking syntax:

Dim X, Y As Integer

Many people, for good reason, would say that this line of Visual Basic 6 code is declaring X and Y as Integer variables. In truth, it is declaring X as a Variant and Y as an Integer. Visual Basic 6 interprets this line of code as if X is being declared without any data type. In Visual Basic .NET, this code now behaves as it should; X and Y are declared as Integer variables. To achieve the same effect in VB6, you would need to include an As Integer clause after each variable name.

Variable Initialization in Declaration

Variables can now be initialized as part of their declaration, which is not any better than having to do it on a separate line, but it certainly seems simpler (and it is a little less typing!).

Dim X As Integer = 5

Object Initialization in Declaration

Just like non-object (or Value) data types, objects can be initialized in their declaration using one of two alternative forms. Either of these two lines will produce the same result:

Dim myForm As New Form()
Dim myForm As Form = New Form()

Obviously, the first version is shorter and simpler, but it carries with it a bit of a stigma from the pre-.NET days of Visual Basic and Visual Basic for Applications. If you declared an object As New in VB/VBA prior to Visual Basic .NET, the compiler would wrap every use of that object in code that would check if the object had been initialized, and would initialize it if it were equal to Nothing. The result was inefficient code and possibly worse as the extra bits of wrapper code could actually lead to bugs in your application. Do not worry though; there is absolutely no reason not to use this syntax in Visual Basic .NET.

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

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