Share via


Deciding What Type of Variable to Define 

When you define a variable, you must decide the following characteristics:

  • Its data type — what kind of data it should hold

  • Its lifetime — how long it should continue to exist

  • Its scope — what code should be able to refer to it without qualifying its name

  • Its access level — what code should have permission to read and write to it

Data Type

In the Dim Statement (Visual Basic) that declares the variable, include an As clause specifying the appropriate data type (such as Integer or String). The following pages can help you choose a variable's data type.

For more information, see Data Type Summary (Visual Basic).

Lifetime

The important decision in lifetime is whether it is acceptable for the variable to cease to exist when the module, class, or procedure that declares it ceases to exist.

If the variable does not need to continue existing beyond the lifetime of its containing element, you do not need to do anything else. If the variable needs to continue to exist longer than its containing element, you can include the Static or Shared keyword in its Dim statement. Follow the steps described in How to: Lengthen a Variable's Lifetime.

For more information, see Lifetime in Visual Basic.

Scope

A variable's scope is normally the same as its declaration space, that is, the containing element in which it is declared. You must decide how extensive the variable's scope should be.

Be sure the Dim statement appears at the appropriate level, such as block, procedure, or module level. Follow the steps described in How to: Control the Scope of a Variable.

For more information, see Scope in Visual Basic.

Access Level

Every variable has a default access level that depends where it is declared, that is, in what type of containing element.

If you need to specify an access level other than the default, you can include an access modifier (such as Protected or Private) in its Dim statement. You can do this only for member variables (namely, variables declared outside a procedure). Follow the steps described in How to: Control the Availability of a Variable.

For more information, see Access Levels in Visual Basic.

See Also

Tasks

How to: Lengthen a Variable's Lifetime
How to: Control the Scope of a Variable

Reference

As (Visual Basic)

Concepts

Variable Declaration in Visual Basic
Declared Element Characteristics
Scope in Visual Basic
Access Levels in Visual Basic