Visual Basic 2008 Programming: Business Applications with a Design Perspective
Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9
Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14 Appendix A Appendix B Appendix C Home
Last change: February 13 2016 18:48:19.

 Chapter in PDF

Table of Contents

Chapter 4: Data, Operations, and Built-In Functions
Last change: February 13 2016 18:47:36.

Declaring Constants

Before a named constant can be used in your program, you must make sure that VB can recognize it. Some named constants are predefined and automatically recognized. These are called system constants. You have seen some of these constants in the preceding chapters. For example, you have seen named constants for colors such as Color.Green, Color.Blue, and Color.Red. You have also seen true or false named constants—True and False. Other named constants must be declared before VB can recognize them. These are called symbolic constants. You use the Const statement to declare a symbolic constant. The syntax is as follows:

Const name [As data type] = literal

For example, the following statement declares the named constant Zero to have a constant value of 0. As the syntax in the preceding example suggests, you can also omit As Integer from the declaration without affecting the result.

Const Zero As Integer = 0

Why Name Constants?

Properly named constants can enhance the understandability of the code. When reviewing code, you may not recognize the specific meaning of a particular value, such as 0 or -1. This is particularly true when the constants are used as the property setting of a VB control. Instead, if you code these constants as False (for 0) and True (for -1) in setting the Checked property of a check box, anyone, including yourself, should be able to follow the code much more easily. In addition, in some cases, you may find it necessary to later change the value of a constant. Using a named constant, you need to make the correction in only one place—where the constant is declared. In contrast, you will have to search the entire program for the constant to change if the constant literal was used.

Last change: February 13 2016 18:47:37.