User-Defined Constants - Visual Basic (original) (raw)

A constant is a meaningful name that takes the place of a number or string that does not change. Constants store values that, as the name implies, remain constant throughout the execution of an application. You can use constants that are defined by the controls or components you work with, or you can create your own. Constants you create yourself are described as user-defined.

You declare a constant with the Const statement, using the same guidelines you would for creating a variable name. If Option Strict is On, you must explicitly declare the constant type.

Const Statement Usage

A Const statement can represent a mathematical or date/time quantity:

Const conPi = 3.14159265358979
Public Const conMaxPlanets As Integer = 9
Const conReleaseDate = #1/1/1995#

It also can define String constants:

Public Const conVersion = "07.10.A"
Const conCodeName = "Enigma"

The expression on the right side of the equal sign ( = ) is often a number or literal string, but it also can be an expression that results in a number or string (although that expression cannot contain calls to functions). You can even define constants in terms of previously defined constants:

Const conPi2 = conPi * 2

Scope of User-Defined Constants

A Const statement's scope is the same as that of a variable declared in the same location. You can specify scope in any of the following ways:

For more information, see How to: Declare A Constant.

Avoiding Circular References

Because constants can be defined in terms of other constants, it is possible to inadvertently create a cycle, or circular reference, between two or more constants. A cycle occurs when you have two or more public constants, each of which is defined in terms of the other, as in the following example:

Public Const conA = conB * 2
Public Const conB = conA / 2

If a cycle occurs, Visual Basic generates a compiler error.

See also