In VB 2005, you declare a variable with the Dim (dimension) keyword and you specify its type using the As keyword:
Dim num1 Dim num2 As Integer
The first statement declares num1, by default, to be an Object type. The Object type is the base class of all the classes in the .NET Framework. You can think of the Object type as equivalent to the Variant type in VB 6.
The second statement explicitly declares num2 to be an Integer variable.
The following statements declare num1 as a Short type and then assign a value to it:
'---range: -32768 <--> 32767 Dim num1 As Short num1 = 32767
You should always specify the data type of a variable, because this assures the variable is strongly typed. Strong typing reduces the likelihood of runtime errors and makes your application much more efficient.
In VB 2005, you must declare all of the variables that you use, although you can work around this restriction and use variables without first declaring them with the Option Explicit Off statement. VB 2005 turns on Option Explicit On by default.
As shown in Figure 2-1, when you assign the value of one value type to another (num2 = num1), VB 2005 or more correctly, .NET makes a copy of the value type:
Dim num1 as Short Dim num2 as Short num1 = -32768 num2 = num1
Figure 2-1. Representation of a value type in memory
Contrast this to the reference type. When you assign the value of a reference type to another, it causes the second variable to make a reference to the first without creating another copy of the value. The following example assigns one string variable to another:
Dim str1, str2 As String str1 = "VB" str2 = str1
The memory allocation of str1 and str2 is as shown in the Figure 2-2.
Figure 2-2. Representation of a reference type in memory
Unlike VB 6, with VB 2005, you can declare two variables to be of the same type in a single statement, as follows:
Dim num1, num2 As Short
In VB 2005, you can also declare two variables of different data types in the same statement:
Dim num1 As Short, num2, num3 As Integer
In this case, num1 is declared as Short, and num2 and num3 are both of type Integer.
Unlike VB 6, in VB 2005, you can declare and initialize a variable in the same statement:
Dim num1 As Short = 56
VB 2005 now supports three new unsigned data types: UShort, UInteger, and ULong.
The following statements declare unum as an unsigned 16-bit integer:
Dim unum As UShort unum = 65535