User-Defined Constants (Visual Basic)
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
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
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
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:
To create a constant that exists only within a procedure, declare it within that procedure.
To create a constant available to all procedures within a class, but not to any code outside that module, declare it in the declarations section of the class.
To create a constant that is available to all members of an assembly, but not to outside clients of the assembly, declare it using the
Friendkeyword in the declarations section of the class.
To create a constant available throughout the application, declare it using the
Publickeyword in the declarations section the class.
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.