How to: Declare A Constant (Visual Basic)
You use the
Const statement to declare a constant and set its value. By declaring a constant, you assign a meaningful name to a value. Once a constant is declared, it cannot be modified or assigned a new value.
You declare a constant within a procedure or in the declarations section of a module, class, or structure. Class or structure-level constants are
Private by default, but may also be declared as
Protected Friend for the appropriate level of code access.
The constant must have a valid symbolic name (the rules are the same as those for creating variable names) and an expression composed of numeric or string constants and operators (but no function calls).
Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Personalizing the IDE.
To declare a constant
Write a declaration that includes an access specifier, the
Constkeyword, and an expression, as in the following examples:
Public Const DaysInYear = 365 Private Const WorkDays = 250
When Option Infer is
Offand Option Strict is
On, you must declare a constant explicitly by specifying a data type (
Off, you can declare a constant without specifying a data type with an
Asclause. The compiler determines the type of the constant from the type of the expression. For more information, see Constant and Literal Data Types.
To declare a constant that has an explicitly stated data type
Write a declaration that includes the
Askeyword and an explicit data type, as in the following examples:
Public Const MyInteger As Integer = 42 Private Const DaysInWeek As Short = 7 Protected Friend Const Funday As String = "Sunday"
You can declare multiple constants on a single line, although your code is more readable if you declare only a single constant per line. If you declare multiple constants on a single line, they must all have the same access level (
To declare multiple constants on a single line
Separate the declarations with a comma and a space, as in the following example:
Public Const Four As Integer = 4, Five As Integer = 5, Six As Integer = 44
Constant and Literal Data Types
Constants Overview How to: Declare A Constant User-Defined Constants Constant and Literal Data Types How to: Group Related Constant Values Together Enumerations Overview How to: Declare Enumerations How to: Refer to an Enumeration Member Enumerations and Name Qualification How to: Iterate Through An Enumeration How to: Determine the String Associated with an Enumeration Value When to Use an Enumeration