A variable is an object that holds a value: Dim myVariable as Integer = 15 In this example, myVariable is an object of type Integer. It has been initialized with the value 15. The formal definition for how you create a variable is: Access-Modifier Identifier As Type [= value] Access modifiers are discussed later in this chapter; for now, you'll use Dim.
An identifier is just a name for a variable, method, class, and so forth. In the case shown previously, the variable's identifier is myVariable. The keyword As signals that what follows is the type, in this case Integer. If you are initializing the variable, you follow the type with the assignment operators (=) followed by the value (e.g., 15) 16.2.1.16.2.1.1. Type charactersVariable identifiers may have a type character suffix that indicates the variable's type. For example, rather than writing as Integer you can use the suffix %. Dim myVariable as Integer Dim myVariable% These two lines are identical in effect. Not every type is a character, but you are free to use them for those types that do. The complete set is shown in Table 16-2.
16.2.1.2. Initializing variablesYou are not required to initialize variables. You could write: Dim myVariable as Integer You can then assign a value to myVariable later in your program: Dim myVariable as Integer 'some other code here myVariable = 15 'assign 15 to myVariable You can also change the value of a variable later in the program. That is why they're called variables, their values vary. Dim myVariable as Integer 'some other code here myVariable = 15 'assign 15 to myVariable 'some other code here myVariable = 12 'now it is 12 Technically, a variable is a named storage location with a type. The value 12 is being stored in the named location. You can safely think of a variable as being an object of the type specified. You can assign values to that object and then you can extract those values later. The use of variables is illustrated in Example 16-1. To test this program, open Visual Studio 2005 and create a Console application. Type in the code as shown.
Example 16-1. Initializing and assigning to variablesSub Main( ) Dim myInt As Integer = 7 Console.WriteLine("Initialized myInt: {0}", myInt) myInt = 5 Console.WriteLine("After assignment myInt: {0}", myInt) End Sub Output: Initialized myInt: 7 After assignment myInt: 5 Here, we initialize the variable myInt to the value 7, display that value, reassign the variable with the value 5, and display it again. To display the value we call the shared WriteLine method on the console class (see the sidebar "WriteLine"). 16.2.2. Default ValuesVisual Basic 2005 does not require that you initialize your variables (though it is a very good idea to discipline yourself to do so). If you do not initialize your variable, it will be set to a default value, as shown in Table 16-3.
16.2.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. 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 reassigned. How do you prevent reassignment? The answer is to use a constant. A constant is like a variable except that its value cannot be changed once it is initialized. A constant associates a name with a value, but you cannot change that value while the program runs. Hence, rather than varying, a constant is, well, constant. Constants come in three flavors: literals , symbolic constants , and enumerations. 16.2.3.1. Literal constantsA literal constant is just a value, such as 32. 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 are, together, a literal constant for the Integer value 32, and you can assign them accordingly: Dim myValue as Integer = 32 'assign the literal value 32 to the variable myValue 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: Dim myValue as Double = 32R 'assign literal value 32 as a Double The complete list of literal formats is shown in Table 16-4.
16.2.3.2. Symbolic constantsSymbolic constants assign a name to a constant value. You declare a symbolic constant using the Const keyword and the following syntax: access-modifierConst identifieras type = value; Access modifiers are discussed later; for now, you will use Public. The keyword Const is followed by an identifier (the name of the constant), the keyword As and the type of the constant (e.g., Integer). This is similar to declaring a variable, except that you add the keyword Const, and symbolic constants must be initialized. Once initialized, a symbolic constant cannot be altered. For example: Public Const FreezingPoint As Integer = 32 In this declaration, 32 is a literal constant and FreezingPoint is a symbolic constant of type Integer. Example 16-2 illustrates the use of symbolic constants. Example 16-2. Symbolic constants Sub Main( ) Const FreezingPoint As Integer = 32 ' degrees Farenheit Const BoilingPoint As Integer = 212 Console.WriteLine("Freezing point of water: {0}", FreezingPoint) Console.WriteLine("Boiling point of water: {0}", BoilingPoint) 'FreezingPoint = 0 End Sub End Module Example 16-2 creates two symbolic integer constants: FreezingPoint and BoilingPoint. See the sidebar "Naming Conventions" for symbolic constants.
These constants serve the same purpose as always using the literal values 32 and 212 for the freezing and boiling points of water in expressions that require them, but because these 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 ought to continue to work. To prove to yourself that the constant cannot be reassigned, try uncommenting the last line of the program (shown in bold). When you recompile, you should receive this error: Constant cannot be the target of an assignment 16.2.4. EnumerationsEnumerations provide a powerful alternative to constants . An enumeration is a distinct value type, consisting of a set of named constants (called the enumerator list). If you created two related constants: Const FreezingPoint As Integer = 32 Const BoilingPoint As Integer = 212 you might wish to add a number of other useful constants as well, such as: const LightJacketWeather As Integer = 60; const SwimmingWeather As Integer = 72; const WickedCold As Integer = 0; This process is somewhat cumbersome, and there is no logical connection among these various constants. Visual Basic 2005 provides the enumeration to solve these problems: 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, Short, Integer, and Long). The technical specification of an enumeration is: [access modifiers ] Enum identifier [As type ] membername [ = constant expression] end Enum
For now, let's focus on the rest of this declaration. An enumeration begins with the keyword Enum, which is followed by an identifier, such as: Enum Temperatures The AS keyword defines the underlying type for the enumeration. That is, are you declaring constant Integers, or constant Longs? If you leave out this optional keyword (and often you will) the underlying type will be integer. Example 16-3 rewrites Example 16-2 to use an enumeration. Example 16-3. Using an enumeration, not quite correctlyEnum 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 16-3, you declare enumerated constant Temperatures. Temperatures is an enumeration. The values of the enumeration must be qualified by the enumeration type. That means you cannot just refer to FreezingPoint, but you must use the prefix Temperatures followed by the dot operator. 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 an enumeration to WriteLine what is displayed is its name, not its value. To display the value of an enumerated constant, you must cast the constant to its underlying type (Integer), as shown in Example 16-4. Example 16-4. Casting the enumerated value to fix Example 16-3Sub 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 case, 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 section "Casting." 16.2.5. CastingObjects of one type can be converted into objects of another type. This is called casting , and casting can be either narrowing or widening. A widening conversion or 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. Casting from Short to Integer is, thus, 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. Casting from an Integer to a Short is thus a narrowing conversion. Visual Basic 2005 conversions are either implicit or explicit. 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 16-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 of the nail. 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 are:
the value of First will be 0, Second will be 1, Third will be 20, and Fourth will be 21.
16.2.6. StringsIt is nearly impossible to write a Visual Basic 2005 program without creating strings . A string object holds a string of characters. You declare a string variable using the String keyword much as you would create an instance of any object: Dim myString as String A string literal is created by placing double quotes around a string of letters: "Hello World" It is common to initialize a string variable with a string literal: Dim myString as String = "Hello World" |