Const Statement - Visual Basic (original) (raw)

Declares and defines one or more constants.

Syntax

[ <attributelist> ] [ accessmodifier ] [ Shadows ]
Const constantlist

Parts

attributelist
Optional. List of attributes that apply to all the constants declared in this statement. See Attribute List in angle brackets ("<" and ">").

accessmodifier
Optional. Use this to specify what code can access these constants. Can be Public, Protected, Friend, Protected Friend, Private, or Private Protected.

Shadows
Optional. Use this to redeclare and hide a programming element in a base class. See Shadows.

constantlist
Required. List of constants being declared in this statement.

constant [ , constant ... ]

Each constant has the following syntax and parts:

constantname [ As datatype ] = initializer

Part Description
constantname Required. Name of the constant. See Declared Element Names.
datatype Required if Option Strict is On. Data type of the constant.
initializer Required. Expression that is evaluated at compile time and assigned to the constant.

If you have a value that never changes in your application, you can define a named constant and use it in place of a literal value. A name is easier to remember than a value. You can define the constant just once and use it in many places in your code. If in a later version you need to redefine the value, the Const statement is the only place you need to make a change.

You can use Const only at module or procedure level. This means the declaration context for a variable must be a class, structure, module, procedure, or block, and cannot be a source file, namespace, or interface. For more information, see Declaration Contexts and Default Access Levels.

Local constants (inside a procedure) default to public access, and you cannot use any access modifiers on them. Class and module member constants (outside any procedure) default to private access, and structure member constants default to public access. You can adjust their access levels with the access modifiers.

Rules

Data Type Rules

Behavior

Example 1

The following example uses the Const statement to declare constants for use in place of literal values.

' The following statements declare constants.
Const maximum As Long = 459
Public Const helpString As String = "HELP"
Private Const startValue As Integer = 5

Example 2

If you define a constant with data type Object, the Visual Basic compiler gives it the type of initializer, instead of Object. In the following example, the constant naturalLogBase has the run-time type Decimal.

Const naturalLogBase As Object = CDec(2.7182818284)
MsgBox("Run-time type of constant naturalLogBase is " &
    naturalLogBase.GetType.ToString())

The preceding example uses the ToString method on the Type object returned by the GetType Operator, because Type cannot be converted to String using CStr.

See also