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 Integercreates 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,kAs 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access