Section 5.3. Constants

   

5.3 Constants

Variables 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 Constants

A 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

Type

Literal

Example

Boolean

True, False

Dim booleanValue As Boolean = True

Char

C

Dim charValue As Char = "J"C

Decimal

D

Dim decimalValue As Decimal = 3.1415D

Double

Any floating point number, or R

Dim doubleValue As Double = 3.1415

Dim doubleValue As Double = 3.1415R

Dim doubleValue As Double = 5R

Integer

Any integer value in range, or I

Dim integerValue As Integer = 100

Dim integerValue As Integer = 100I

Long

Any integer value outside the range of type Integer or L

Dim longValue As Long = 5000000000

Dim longValue As Long = 100L

Short

S

Dim shortValue As Short = 100S

Single

F

Dim singleValue As Single = 3.14F

String

""

Dim stringValue As String = "Hello world!"

5.3.2 Symbolic Constants

Symbolic 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 constants
 Module 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.

Naming Conventions

Microsoft has promulgated white papers on how you should name the variables, constants, and other objects in your program. They define two types of naming conventions: Camel notation and Pascal notation.

In Camel notation, names begin with a lowercase letter. Multiword names (e.g., "my button") are written with no spaces and no underscore and with each word after the first capitalized. Thus, the correct name for "my button" is myButton.

Pascal notation is just like Camel notation except that the first letter is also uppercase (e.g., FreezingPoint).

Microsoft suggests that variables be written with Camel notation and constants with Pascal notation. In later chapters, you'll learn that member variables and methods are named using Camel notation, while classes are named using Pascal notation.

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 Enumerations

Enumerations 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.

In a specification statement, anything in square brackets is optional. That is, you can declare an Enum with no access modifiers or base-type, or without assigning a value. Note that the base-type is optional, even if Option Strict is On.

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 enumeration
 Module 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 value
 Module 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.

If Option Strict is set On, Enums are treated as formal types; that is, they are not just a synonym for another type, they are a type in their own right. Therefore an explicit conversion is required to convert between an Enum type and an integral type (such as Integer, Long, etc.).

5.3.4 About Casting

Objects 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.

CBool( )

Converts any valid string (e.g., "True") or numeric expression to Boolean. Numeric nonzero values are converted to True, zero is converted to False.

CByte( )

Converts numeric expression in range 0 to 255 to Byte. Round any fractional part.

CChar( )

Returns the first character of a string as a Char.

CDate( )

Converts any valid representation of a date or time to the Date type (e.g., "January 1, 2002" is converted to the corresponding Date type).

CDbl( )

Converts any expression that can be evaluated as a number to a Double if it is in the range of a Double.

CDec( )

Converts any expression that can be evaluated as a number to a Decimal if it is in the range of a Decimal.

CInt( )

Converts any expression that can be evaluated as a number to a Integer if it is in the range of a Integer; rounds fractional part.

CLng( )

Converts any expression that can be evaluated as a number to a Long if it is in the range of a Long; rounds fractional part.

CObj( )

Converts any expression that can be interpreted as an Object to an Object.

CShort( )

Converts any expression that can be evaluated as a number to a Short if it is in the range of a Short.

CStr( )

If Boolean, converts to the string "True" or "False." If the expression can be interpreted as a date, returns a string expression of the date. For numeric expressions, the returned string represents the number.

CType( )

This is a general purpose conversion function that uses the syntax:

 CType(   expression   ,   typename   ) 

where expression is an expression or a variable, and typename is the datatype to convert to. The first conversion in Example 5-4 can be rewritten from:

 System.Console.WriteLine( _           "Freezing point of water: {0}", _           CInt(Temperatures.FreezingPoint)) 

to:

 System.Console.WriteLine( _           "Freezing point of water: {0}", _  CType(Temperatures.FreezingPoint, Integer))  
   


Learning Visual Basic. NET
Learning Visual Basic .Net
ISBN: 0596003862
EAN: 2147483647
Year: 2002
Pages: 153
Authors: Jesse Liberty

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net