Variable Declarations


Visual Basic .NET Unleashed
By Paul Kimmel
Table of Contents
Chapter 2.  Out with the Old, In with the New

Variable Declarations

Variable declarations have undergone some changes that will make them more convenient to use in VB .NET.

In VB6 you couldn't declare multiple variables of a specific type. If you declared a list of variables in VB6, all variables except the last variable in the list were variants. VB6 didn't support variable declaration and initialization in the same statement either. Each of the subsections describes the different styles of VB .NET variable declaration. The comparisons to the old style are included to help you find your bearings.

Declaring and Initializing a Single Variable

VB6 required that you declare and initialize a variable in two separate statements ( assuming that Option Explicit was On). VB .NET supports doing both in a single statement. Listing 2.8 contains several VB6 variable declarations and initialization statements, followed by the VB .NET equivalent.

Listing 2.8 VB6 variable declaration and initialization statements
  1:  Private Sub Command1_Click()  2:   3:  Dim I As Integer  4:  I = 5  5:  Dim S As String  6:  S = "Jello Mold"  7:   8:  Dim D As Date  9:  D = Now  10:   11:  Dim F As Double  12:  F = D  13:   14:  Dim S1 As String: S1 = "Some More Text"  15:   16:  Debug.Print S1  17:   18:  End Sub 

As you can determine from Listing 2.8, each of the variables are declared in Dim statements and initialized after that. (Note on line 12 that a Double is initialized with a Date; that's a no-no in VB .NET.) You may also declare and initialize a variable on the same line in VB6, as line 14 demonstrates , but this constitutes two separate statements. Listing 2.9 demonstrates the more concise VB .NET equivalent code.

Listing 2.9 The VB6 code from Listing 2.8, revised for VB .NET
  1:  Private Sub button4_Click(ByVal sender As System.Object, _  2:  ByVal e As System.EventArgs) Handles button4.Click  3:   4:  Dim I As Integer = 5  5:  Dim S As String = "Jello Mold"  6:  Dim D As Date = Now()  7:  Dim F As Double = D.ToOADate()  8:  Dim S1 As String = "Some More Text"  9:  Debug.WriteLine(S1)  10:   11:  End Sub 

Line 1 demonstrates the button-click event handler. Event handlers are covered in detail in Chapter 8, "Adding Events." For now, suffice it to say that Command controls are Button controls in VB .NET, event handlers get a reference to the invoking object, and argument parameters passed in the System.EventArgs reference. Handles is a new keyword, also discussed in more detail in Chapter 8.


As a good, general programming practice, always provide an initial value for variables. Initial values provide you with a reliable reference point.

The code on lines 4 through 9 of Listing 2.9 performs precisely the same tasks as Listing 2.8 from VB6 does. Note that declarations and initializations are contained in a single statement, and initial values can be derived from functions. Of course, you can split declaration and initialization, but unless you have a very good reason not to, provide an initial value when you declare a variable.

Multivariable Declaration

Declaring multiple variables in the same statement in VB6 resulted in one typed variable and everything else was a Variant. In addition to variant types not being supported in VB .NET, this is seldom if ever what you want. Listing 2.10 demonstrates multiple variable declarations in VB6 code followed by the VB .NET code. A brief synopsis follows each listing.

Listing 2.10 VB6 code declaring multiple variables in a single statement
  1:  Private Sub Command2_Click()  2:   3:  ' VB6 Multiple Variable Declaration  4:  Dim I, J, K As Integer  5:   6:  I = 5  7:  J = "Ooops!"  8:  K = 15  9:   10:  End Sub 

In Listing 2.10, I and J look as if they might be integers, but they are actually variants. Only K is an integer. Hence we can assign J a string as demonstrated in line 7. This is never what you want. If you tried to assign a string to K, you would get a compiler error. You want the compiler to check for data misuse as does VB .NET. Listing 2.11 demonstrates the VB .NET equivalent.

Listing 2.11 Declaring multiple variables in VB .NET
  1:  Option Strict On  2:   3:  Module Module3  4:   5:  Sub MultipleVariables()  6:   7:  ' VB6 Multiple Variable Declaration  8:  Dim I, J, K As Integer  9:   10:  I = 5  11:  J = "Ooops!" ' Causes compiler error  12:  K = 15  13:   14:  End Sub  15:   16:  End Module 


The code in Listing 2.11 intentionally doesn't compile. The compiler will indicate that Option Strict doesn't allow an implicit conversion from string to integer. The implication is that each of I, J, and K are integer types, whereas only K is an Integer in the VB6 code in Listing 2.10.

Listing 2.11 is identical to Listing 2.10, except the code is written in a vanilla procedure in Listing 2.11 and an event handler in Listing 2.10. Listing 2.11 also demonstrates the placement of the procedure in a module and the Option Strict On statement.


Always write all code with Option Explicit On and Option Strict On. (I imagine that future versions of VB .NET will remove these options entirely, ensuring strict and explicit code.) You always want the compiler to catch as many errors as it can, followed by handled exceptions at runtime (see the section on exception handling later in this chapter). The compiler is very good at detecting and helping you resolve errors; by writing explicit code, you're enabling the compiler to do a lot of work for you.

Keep in mind that Option Strict On must be true for the compiler to catch the assignment of a string to an integer as demonstrated in Listing 2.11. With Option Strict Off, the error will manifest itself as an InvalidCastException at runtime.

Multiple Initializers Not Allowed

Visual Basic .NET supports multiple variable declarations and ensures that they are all the type specified in the As clause. However, when you use multiple declarators you may not include initialization. For example, the code fragment

 Dim I , J , K As Integer = 3, 4, 5 

represents invalid code even in VB .NET. Remove the initial values and the code is correct.

Declarator is the term used to describe a variable declaration and initialization statement. For example, Dim D As Datetime = Now() is a declarative statement, or a declarator.

Defining Constants

Constant declarations must include the data type with Option Strict On in Visual Basic .NET. In VB6 the data type was determined by the initial value; VB .NET will determine the data type if it's not explicitly included in an As clause and Option Strict Off is True. The first fragment demonstrates a VB6 constant declaration and the second demonstrates the same declaration in VB .NET using the data type.

 ' VB6 Code Const ADate = #12:00:00 AM# Debug.Print ADate 

Here is the VB .NET equivalent:

 ' VB.NET Code Const ADate As DateTime = #12:00:00 AM# Debug.WriteLine(ADate) 

Notice that the biggest difference is the presence of the DataType in VB .NET. Both VB6 and VB .NET require that you use a constant value to initialize a constant; the value may not be derived from a function.

Instantiating Objects

Refer to Chapter 7, "Creating Classes," for an extensive discussion of object-oriented principles. In this section I will present a brief introduction, so you can progress with the examples between now and Chapter 7. Let's examine a few simple concepts before we look at creating objects.

A class is a description of an entity. Classes indicate what methods , properties, and fields you will find in instances of a kind. A metaclass is a variable of the class type. Metaclasses are returned by the GetType() polymorphic method introduced in the Object class. When you're using a class as if it were an object, at that time the class is referred to as a metaclass. Instance and object are synonyms. An instance, or object, is when you declare a variable whose type is a class and allocate memory to it. This process is referred to as instantiating an object, or creating an instance of an object.

Objects are instantiated using the New keyword. This is similar to how you created objects in VB6; however, classes in VB .NET have constructors. A constructor is a method whose job it is to initialize objects. Objects are created in VB .NET with code similar to the following:

 Dim List As New Collection() 

The code fragment declares and initializes an instance of the Collection class. The class is Collection and the object is List. The type of the object List is Collection. Note the addition of the parentheses in VB .NET.

Parameterized constructors are constructor methods that can accept arguments. In many languages the constructor method has the same name as the class, and in others a special name is used for the constructor by convention. In VB .NET constructors are named New, but the parameters are passed to constructors between the parentheses following the class name . For example, a DateTime type is a ValueType which in turn is a subclass of the Object class. Hence you may use the more verbose version of construction for DateTime objects as demonstrated next .

 Dim MyDate As New DateTime(1966, 2, 12) Debug.WriteLine(MyDate) 

The verbose form of the DateTime declaration shows the New keyword and the parameters passed to the DateTime constructor. In the case of DateTime types there are actually seven overloaded constructors. An overloaded constructor is like any overloaded method.

An overloaded method is a method or methods in the same class that have identical names but distinguishing parameter signatures.

Method overloading wasn't supported in VB6 but is supported in VB .NET. Read Chapter 7, "Creating Classes," for more on advanced object-oriented idioms supported in VB .NET.

Initializer Lists

The admonition to provide initial values to variables applies to complex data types too. In the case of classes the initialization is accomplished by the constructor. Structures can have constructors too, so we can easily supply initial values to structures. What about arrays?

Array declaration and initialization is slightly more complex than declaring Integer types, but you can declare and initialize arrays in a single statement in VB .NET. The following statement declares and initializes an array demonstrating an initializer list.

 Dim MyArray() As Integer = {1, 2, 3, 4} 

The array is declared as an unbound array of type Integer. The initializer list ({}) constructs the array with four elements: 1, 2, 3, 4. You may not provide initializer lists for arrays declared with a specific size . For example, the following is an invalid statement:

 Dim MyArray(4) As Integer = {1, 2, 3, 4} 

Arrays are classes defined in the System.Array namespace. For more information on arrays and array methods, see the section "Arrays and Collections" later in this chapter.


Visual BasicR. NET Unleashed
Visual BasicR. NET Unleashed
Year: 2001
Pages: 222 © 2008-2017.
If you may any questions please contact us: