The constants refer to fixed values that the program may not alter during its execution, and these values are also known as literals.
You can use the Const
statement to declare a constant and set its value. Once a constant is declared, it cannot be modified or assigned a new value.
Private
by default, but may also be declared as Public
, Friend
, Protected
, or Protected Friend
for the appropriate level of code access.The following example demonstrates the declaration and use of a constant value.
Const DaysInYear = 365
Const WorkDays = 250
Console.WriteLine(DaysInYear)
Console.WriteLine(WorkDays)
The following example shows the declaration constants by specifying their data types us As
keyword.
Const MyInteger As Integer = 42
Const DaysInWeek As Short = 7
Const Sunday As String = "Sunday"
Console.WriteLine(MyInteger)
Console.WriteLine(DaysInWeek)
Console.WriteLine(Sunday)
You can declare several constants in one declaration statement by specifying the name for each one and separate the declarations with a comma and space as shown below.
Const num1 As Integer = 4, num2 As Integer = 5, str1 As String = "Test String"
Console.WriteLine(num1)
Console.WriteLine(num2)
Console.WriteLine(str1)
A Const
statement's scope is the same as that of a variable declared in the same location. You can specify the scope in any of the following ways.