You can use constants that are intrinsic to the object model for controls or components you work with, or you can create your own. Constants you create yourself are described as being 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/95#
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:
- 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 Friend keyword in the declarations section of the class.
- To create a constant available throughout the application, declare it using the Public keyword in the declarations section the class.
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.
Const Statement | String Class | Constant and Literal Data Types | Declaring Constants | Option Strict Statement | Constants Overview | Enumerations Overview | Declaring Enumerations | Enumerations and Name Qualification | Intrinsic Constants and Enumerations | Choice of Variable Scope