Variable Declaration and Initialization

When you are declaring a data type as a local variable (e.g., a variable within a member scope), you do so using the Dim and As keywords. By way of a few examples:

Sub MyMethod()

' Local variables are declared as follows: ' Dim variableName As dataType

Dim age As Integer Dim firstName As String Dim isUserOnline As Boolean End Sub

One helpful syntactic change that has occurred with the release of the .NET platform is the ability to declare a sequence of variables on a single line of code. VB6 also supported this ability, but the semantics were a bit nonintuitive and a source of subtle bugs. For example, under VB6, if you do not explicitly set the data types of each variable, the unqualified variables were set to the VB6 Variant data type:

' In this line of VB6 code, varOne ' is implicitly defined as a Variant!

Dim varOne, varTwo As Integer

This behavior is more than a bit annoying, given that the only way you are able to define multiple variables of the same type under VB6 is to write the following slightly redundant code:

Dim varOne As Integer, varTwo As Integer or worse yet, on multiple lines of code:

Dim varOne As Integer Dim varTwo As Integer

Although these approaches are still valid using VB 2008, when you declare multiple variables on a single line, they all are defined in terms of the specified data type. Thus, in the following VB 2008 code, you have created two variables of type Integer:

Sub MyOtherMethod()

' In this line of VB 2008 code, varOne ' and varTwo are both of type Integer! Dim varOne, varTwo As Integer End Sub

On a final note, VB 2008 now supports the ability to assign a value to a variable directly at the point of declaration. To understand the significance of this new bit of syntax, consider the fact that under VB6, you were forced to write the following:

VB 2008 allows you to streamline variable assignment using the following notation: Sub MyMethod()

' Local data can be initialized at the time of declaration: ' Dim variableName As dataType = initialValue

Dim age As Integer = 36 Dim firstName As String = "Sid" Dim isUserOnline As Boolean = True End Sub

Was this article helpful?

0 0

Post a comment