5.3 ConstantsVariables are a powerful tool, but there are times when you want to manipulate a defined value, one whose value you want to ensure remains constant. A constant is like a variable in that it can store a value. However, unlike with a variable, the value of a constant cannot be changed while the program runs. For example, you might need to work with the Fahrenheit freezing and boiling points of water in a program simulating a chemistry experiment. Your program will be clearer if you name the variables that store these values FreezingPoint and BoilingPoint, but you do not want to permit their values to be changed while the program is executing. The solution is to use a constant. Constants come in three flavors: literals , symbolic constants , and enumerations . 5.3.1 Literal ConstantsA literal constant is just a value. For example, 32 is a literal constant. It does not have a name; it is just a literal value. And you can't make the value 32 represent any other value. The value of 32 is always 32. You can't assign a new value to 32; and you can't make 32 represent the value 99 no matter how you might try. When you write an integer as a literal constant, you are free just to write the number. The characters 32 make up a literal constant for the Integer value 32, and you can assign them accordingly : Dim myValue As Integer = 32 'assign the literal value 32 If you want to assign a different type, however, you will want to use the correct format. For example, to designate the value 32 as a Double (rather than as an Integer), you will append the character R, as in the following: 32R ' the double value 32 The complete list of literal formats is shown in Table 5-4. Table 5-4. Literal formats
5.3.2 Symbolic ConstantsSymbolic constants assign a name to a constant value. You declare a symbolic constant using the following syntax: access-modifier Const identifier As type = value; Access modifiers are discussed in Chapter 8; for now you will use public . The Const keyword is followed by an identifier (the name of the constant), the as keyword, the type of the constant (e.g., Integer), then the assignment operator ( = ), and the value with which you'll initialize the constant. This is similar to declaring a variable, except that you start with the keyword Const and symbolic constants must be initialized. Once initialized a symbolic constant cannot be altered . For example, in the following declaration, 32 is a literal constant and FreezingPoint is a symbolic constants of type Integer: Public Const FreezingPoint As Integer = 32 Example 5-2 illustrates the use of symbolic constants. Example 5-2. Symbolic constantsModule Module1 Sub Main( ) Const FreezingPoint As Integer = 32 ' degrees Farenheit Const BoilingPoint As Integer = 212 System.Console.WriteLine("Freezing point of water: {0}", FreezingPoint) System.Console.WriteLine("Boiling point of water: {0}", BoilingPoint) ' FreezingPoint = 0 End Sub End Module Example 5-2 creates two symbolic integer constants: FreezingPoint and BoilingPoint. See the sidebar Naming Conventions for a discussion of how to name symbolic constants.
These constants serve the same purpose as using the literal values 32 and 212, for the freezing and boiling points of water, respectively, in expressions that require them. However, because the constants have names, they convey far more meaning. Also, if you decide to switch this program to Celsius, you can reinitialize these constants at compile time to 0 and 100, respectively; and all the rest of the code should continue to work. To prove to yourself that the constant cannot be reassigned, try uncommenting the third from the last line of the preceding program (it appears in bold), by removing the quote mark: FreezingPoint = 0 Then when you recompile, you'll receive this error: Constant cannot be the target of a reassignment 5.3.3 EnumerationsEnumerations provide a powerful alternative to literal or simple symbolic constants. An enumeration is a distinct value type, consisting of a set of named constants (called the enumerator list ). In Example 5-2, you created two related constants: Const FreezingPoint As Integer = 32 ' degrees Farenheit Const BoilingPoint As Integer = 212 You might want to add a number of other useful constants to this list as well, such as: Const LightJacketWeather As Integer = 60 Const SwimmingWeather As Integer = 72 Const WickedCold As Integer = 0 Notice, however, that this process is somewhat cumbersome; also this syntax shows no logical connection among these various constants. VB.NET provides an alternate construct, the enumeration, which allows you to group logically related constants, as in the following: Enum Temperatures CelsiusMeetsFahrenheit = -40 WickedCold = 0 FreezingPoint = 32 LightJacketWeather = 60 SwimmingWeather = 72 BoilingPoint = 212 End Enum Every enumeration has an underlying type, which can be any integral type (Byte, Integer, Long, or Short). The technical specification of an enumeration is: [ access modifiers ] Enum identifier [As base-type ] enumerator-list [ = constant-expression ] End Enum The optional access modifiers are considered in Chapter 8.
For now, let's focus on the rest of this declaration. An enumeration begins with the Enum keyword, which is followed by an identifier, such as: Enum Temperatures The base-type is the underlying type for the enumeration. That is, are you declaring constant Integers or constant Longs? If you leave out this optional value (and often you will), it defaults to Integer, but you are free to use any of the integral types (e.g., Long). For example, the following fragment declares an enumeration of Longs: Enum ServingSizes As Long Small = 1 Regular = 2 Large = 3 End Enum Notice that the key portion of an Enum declaration is the enumerator list, which contains the constant assignments for the enumeration, each separated by a newline. Example 5-3 rewrites Example 5-2 to use an enumeration. Example 5-3. Using an enumerationModule Module1 Enum Temperatures WickedCold = 0 FreezingPoint = 32 LightJacketWeather = 60 SwimmingWeather = 72 BoilingPoint = 212 End Enum 'Temperatures Sub Main( ) System.Console.WriteLine( _ "Freezing point of water: {0}", _ Temperatures.FreezingPoint) System.Console.WriteLine( _ "Boiling point of water: {0}", _ Temperatures.BoilingPoint) End Sub End Module Output : Freezing point of water: FreezingPoint Boiling point of water: BoilingPoint In Example 5-3, you declare an enumerated constant called Temperatures. When you want to use any of the values in an enumeration in a program, the values of the enumeration must be qualified by the enumeration name. You cannot just refer to FreezingPoint; instead, you use the enumeration identifier (Temperatures) followed by the dot operator and then the enumerated constant (FreezingPoint). This is called qualifying the identifier FreezingPoint. Thus, to refer to the FreezingPoint, you use the full identifier Temperatures.FreezingPoint. Unfortunately, if you pass the name of a constant within an enumeration to the WriteLine( ) method, the name is displayed, not the value. In order to display the value of an enumerated constant, you must cast the constant to its underlying type (in this case, Integer), as shown in Example 5-4. Example 5-4. Casting the enumerated valueModule Module1 Enum Temperatures WickedCold = 0 FreezingPoint = 32 LightJacketWeather = 60 SwimmingWeather = 72 BoilingPoint = 212 End Enum 'Temperatures Sub Main( ) System.Console.WriteLine( _ "Freezing point of water: {0}", _ CInt(Temperatures.FreezingPoint)) System.Console.WriteLine( _ "Boiling point of water: {0}", _ CInt(Temperatures.BoilingPoint)) End Sub End Module When you cast a value (in this example, using the CInt( ) function) you tell the compiler: "I know that this value is really of the indicated type." In this case, you are saying: "Treat this enumerated constant as an Integer." Since the underlying type is Integer, this is safe to do. See the next section, Section 5.3.4, for more information about the use of CInt( ) and the other casting functions. In Example 5-4, the values in the two enumerated constants, FreezingPoint and BoilingPoint, are both cast to type Integer; then those Integer values are passed to WriteLine( ) and displayed. Each constant in an enumeration corresponds to a numerical value. In Example 5-4, each enumerated value is an integer. If you don't specifically set it otherwise , the enumeration begins at 0, and each subsequent value counts up from the previous. Thus, if you create the following enumeration: Enum SomeValues First Second Third = 20 Fourth End Enum the value of First will be 0, Second will be 1, Third will be 20, and Fourth will be 21.
5.3.4 About CastingObjects of one type can be converted into objects of another type. This is called casting. Casting can be either narrowing or widening. The way casting is invoked is either explicit or implicit. A widening cast is one in which the conversion is to a type that can accommodate every possible value in the existing variable type. For example, an Integer can accommodate every possible value held by a Short. Thus, casting from Short to Integer is a widening conversion. A narrowing cast is one in which the conversion is to a type that may not be able to accommodate every possible value in the existing variable type. For example, a Short can accommodate only some of the values that an Integer variable might hold. Thus, casting from an Integer to a Short is a narrowing conversion. In VB.NET, conversions are invoked either implicitly or explicitly. In an implicit conversion, the compiler makes the conversion with no special action by the developer. With an explicit conversion, the developer must use a special function to signal the cast. For example, in Example 5-4, you use the CInt function to explicitly cast the Enumerated value to an Integer. The semantics of an explicit conversion are: "Hey! Compiler! I know what I'm doing." This is sometimes called " hitting it with the big hammer " and can be very useful or very painful, depending on whether your thumb is in the way. Whether a cast is implicit or explicit is affected by the Option Strict setting. If Option Strict is On (as it always should be), only widening casts can be implicit. The explicit cast functions follow. Refer back to Table 5-1 for information about the ranges covered by the various numeric types.
|