How to: Declare A Constant

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 Public, Friend, Protected, or 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).

Note

  The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is described in Help depending on your active settings or edition. This Help page was written with General Development Settings in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Visual Studio Settings.

To declare a constant

  • Write a declaration that includes an access specifier, the Const keyword, and an expression, as in the following examples:

    Public Const DaysInYear = 365
    Private Const WorkDays = 250
    

    When Option Strict is On, you must declare a constant explicitly by specifying a data type (Boolean, Byte, Char, DateTime, Decimal, Double, Integer, Long, Short, Single, or String). When Option Strict is Off, the constant is assigned a data type by the compiler. For more information, see Constant and Literal Data Types.

To declare a constant with Option Strict On

  • With Option Strict On, write a declaration that includes the As keyword 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 (Public, Private, Friend, Protected, or Protected Friend).

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
    

See Also

Tasks

How to: Declare Enumerations

Concepts

Constant and Literal Data Types

Enumerations Overview

Constants Overview

Enumerations and Name Qualification

Intrinsic Constants and Enumerations

Reference

Const Statement (Visual Basic)

Option Strict Statement

Other Resources

Constants and Enumerations in Visual Basic