Declaring Variables and Constants VB.NET

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:

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

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:

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:

to declare an Integer variable and initialize it to 5. Similarly, we can declare and initialize more than
one variable on a single line:

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 manner:

Dim obj As MyClass

However, this declaration does not create an object variable, and the variable is equal to Nothing at this point. Object creation requires an explicit call to the object's constructor, as in:

Variables and constants can be declared with any of the following access modifiers:

  • Public
  • Private
  • Friend
  • Protected
  • Protected Friend

Note also that the Dim keyword can be used as well, but it often defaults to one of the previously mentioned access modifiers. This is potentially confusing, so the Dim keyword should only be used when required, as it is for local variables.Access modifiers help to specify the scope and accessibility of the variable.
Constant declarations are analogous to variable declarations and have the form:

where AccessModifier is one of the access modifiers defined earlier. Note that when Option Strict is On (the default), all constant declarations must have a declared type.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

VB.NET Topics