O'Reilly logo

VB.NET Language in a Nutshell, Second Edition by Steven Roman PhD, Paul Lomax, Ron Petrusha

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Declaring Variables and Constants

A variable declaration is an association of a variable name with a data type. In and of itself, this does not imply variable creation. However, for nonobject variables, a variable declaration does create a variable. A declaration such as:

Dim x As Integer

creates an Integer variable named x. We can also write:

Dim x As Integer = New Integer(  )

which emphasizes the role of the constructor function for the Integer data type. (The constructor is the function that VB.NET uses to create the variable.)

When multiple variables are declared on the same line, if a variable is not declared with an explicit type declaration, 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, which is VB 6’s default data type.)

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 it 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

Note that in this case, each variable that you declare must explicitly be assigned a data type. You cannot assign each variable an explicit value without explicitly declaring the data type of each variable.

Object variables are declared in the same ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required