16.2. Variables


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.

The keyword Dim is short for dimension. This term dates back to the early days of BASIC programming, and is essentially vestigial.


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 characters

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

Table 16-2. Type characters

Type

Type character

Usage

Decimal

@

Dim decimalValue@ = 123.45

Double

#

Dim doubleValue# = 3.14159265358979

Integer

%

Dim integerValue% = 1

Long

&

Dim longValue& = 123456789

Single

!

Dim singleValue! = 3.1415

String

$

Dim stringValue$ = "Hello world"


While type characters were preserved in the Visual Basic .NET language, many developers feel they should be avoided, and that spelling out the type makes for clearer and easier-to-maintain code.


16.2.1.2. Initializing variables

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

WriteLine

The .NET Framework provides a useful method for displaying output on the screen in console applications. The details of this method, System.Console.WriteLine( ), will become clearer as we progress through the book, but the fundamentals are straightforward. You call the method as shown in Example 16-1, passing in a string that you want printed to the console (the screen).

You can also pass in substitution parameters. Here's how it works. You place a number between braces:

 System.Console.WriteLine("After assignment, myVariable: {0}", myVariable) 

and you follow the quoted string with a comma and then a variable name. The value of the variable will be substituted into the parameter. Assuming myVariable has the value 15, the statement shown above causes the following to display:

 After assignment, myVariable: 15 

You can have more than one parameter, and the variable values will be substituted in order:

 System.Console.WriteLine("After assignment, myVariable: {0} and myOtherVariable: {1}",  myVariable, myOtherVariable); 

Assuming myVariable has the value 15, and myOtherVariable has the value 20, this will cause the following to display:

 After assignment, myVariable: 15 and myOtherVariable: 20. 


Example 16-1. Initializing and assigning to variables
    Sub 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 Values

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

Table 16-3. Default values for uninitialized variables

Data type

Default value

All numeric types

0

Boolean

False

Date

01/01/0001 12:00:00 AM

Decimal

0

Object

Nothing

String

"" (zero length string)


Object defaults to Nothing. This keyword indicates that the variable is not associated with any object. You can assign the keyword Nothing to a reference to an object of any type.


16.2.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. 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 constants

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

Table 16-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"


16.2.3.2. Symbolic constants

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

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, but each word after the first begins with an uppercase letter (e.g., 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. Later on you'll learn that member variables and methods are named with camel notation, but classes are named with Pascal notation.


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

Enumerations 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 

In a specification statement like this, anything in square brackets is optional. That is, you can declare an Enum with no base type. The base type is optional, even if Strict is On, and if you don't define a base type, integer is assumed.


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 correctly
    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 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-3
    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 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. Casting

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


CBool

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


CByte

Converts numeric expression in range 0 to 255 to Byte. Rounds 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 Date (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 in the range of a Double.


CDec

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


CInt

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


CLng

Converts any expression that can be evaluated as a number to a Long if 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 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 data type to convert to. The first conversion in Example 16-4:

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

can be rewritten as:

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

The value in the enumerated constant is cast to an integer, and that integer value is passed to WriteLine and displayed. If you don't specifically set it otherwise, the enumeration begins at 0 and each subsequent value counts up from the previous one.

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 Enum and an Integer types.


16.2.6. Strings

It 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" 



Programming Visual Basic 2005
Programming Visual Basic 2005
ISBN: 0596009496
EAN: 2147483647
Year: 2006
Pages: 162
Authors: Jesse Liberty

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