Some variables don’t change value during the execution of a program. These variables are constants that appear many times in your code. For instance, if your program does math calculations, the value of pi (3.14159. . .) might appear many times. Instead of typing the value 3.14159 over and over again, you can define a constant, name it pi, and use the name of the constant in your code. The statement
circumference = 2 * pi * radius
Code language: VB.NET (vbnet)
is much easier to understand than the equivalent
circumference = 2 * 3.14159 * radius
Code language: VB.NET (vbnet)
You could declare pi as a variable, but constants are preferred for two reasons:
Constants don’t change value. This is a safety feature. After a constant has been declared, you can’t change its value in subsequent statements, so you can be sure that the value specified in the constant’s declaration will take effect in the entire program.
Constants are processed faster than variables. When the program is running, the values of constants don’t have to be looked up. The compiler substitutes constant names with their values, and the program executes faster.
The manner in which you declare constants is similar to the manner in which you declare variables, except that you use the Const keyword and in addition to supplying the constant’s name, you must also supply a value, as follows:
Const constantname As type = value
Code language: VB.NET (vbnet)
Constants also have a scope and can be Public or Private. The constant pi, for instance, is usually declared in a module as Public so that every procedure can access it:
Public Const pi As Double = 3.14159265358979
Code language: VB.NET (vbnet)
The name of the constant follows the same rules as variable names. The constant’s value is a literal value or a simple expression composed of numeric or string constants and operators. You can’t use functions in declaring constants. By the way, the specific value I used for this example need not be stored in a constant. Use the pi member of the Math class instead (Math.pi).
Constants can be strings, too, like these:
Const ExpDate = #31/12/1997#
Const ValidKey = "A567dfe"
Code language: VB.NET (vbnet)