A variable is a storage location with a type. The type will be one of the intrinsic types (variables of user-defined types are called objects, and are explained in Chapter 5). In the examples in Section 3.2.3, both myInteger and myDouble are variables. Variables can have values assigned to them, and those values can be changed programmatically.
WriteLine( )The .NET Framework provides a useful method for writing output to the screen. The details of this method, System.Console.WriteLine( ), will become clearer as we progress through the book, but the fundamentals are straightforward. You call WriteLine( ) in Example 3-1, passing in a String that you want printed to the console (the screen) and, optionally, parameters that will be substituted. In the following example: System.Console.WriteLine("After assignment, myInteger: {0}", myInteger) the String "After assignment, myInteger:" is printed as-is, followed by the value in the variable myInteger. The location of the substitution parameter {0} specifies where the value of the first output variable, myInteger, will be displayed, in this case at the end of the String. We'll see a great deal more about WriteLine( ) in later chapters. |
You create a variable by declaring its type and then giving it a name. You can initialize the variable when you declare it, and you can assign a new value to that variable at any time, changing the value held in the variable. Example 3-1 initializes the variable myInteger with the value 7, displays that value, reassigns the variable with the value 5, and displays it again.
Option Strict On Imports System Module Module1 Sub Main( ) Dim myInteger As Integer = 7 Console.WriteLine("Initialized, myInteger: {0}", _ myInteger) myInteger = 5 Console.WriteLine("After assignment, myInteger: {0}", _ myInteger) End Sub End Module Output: Initialized, myInteger: 7 After assignment, myInteger: 5
If you create a variable but do not initialize it with a value, Visual Basic .NET will provide a default value for you. The default values for the intrinsic types are as follows:
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 a variable whose value cannot be changed.
Constants come in three flavors: literals, symbolic constants, and enumerations. In this assignment:
x = 32
the value 32 is a literal constant. The value of 32 is always 32. You can't assign a new value to 32; you can't make 32 represent the value 99 no matter how you might try.
Symbolic constants assign a name to a constant value. You declare a symbolic constant using the Const keyword and the following syntax:
Const value As type = identifier
A constant must be initialized when it is declared, and once initialized it cannot be altered. For example:
Const FreezingPoint As Integer = 32
In this declaration, 32 is a literal constant and FreezingPoint is a symbolic constant of type Integer. Example 3-2 illustrates the use of symbolic constants.
Option Strict On Imports System Module Module1 Sub Main( ) Const FreezingPoint As Integer = 32 ' Farenheit Const BoilingPoint As Integer = 212 Console.WriteLine("Freezing point of water: {0}", _ FreezingPoint) Console.WriteLine("Boiling point of water: {0}", _ BoilingPoint) ' BoilingPoint = 100 End Sub End Module
Example 3-2 creates two symbolic Integer constants: FreezingPoint and BoilingPoint. As a matter of style, constant names are written in Pascal notation (initial uppercase), but this is certainly not required by the language.
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 assignment to BoilingPoint:
BoilingPoint = 100
When you recompile you should receive this error:
Constant cannot be the target of an assignment
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).
In Example 3-2, 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 to this list, 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 .NET provides the enumeration to solve these problems:
Public Enum Temperatures CelsiusMeetsFahrenheit = -40 WickedCold = 0 FreezingPoint = 32 LightJacketWeather = 60 SwimmingWeather = 72 BoilingPoint = 212 End Enum 'Temperatures
Every enumeration has an underlying type, which can be any integral type (Integer, Short, Long, etc.) except for Char. The syntax of an enumeration is:
[attributes ] [access modifiers ] Enum identifier [As base-type ] enumerator-list [ = constant-expression ] End Enum
The optional attributes and modifiers are considered later in this book. For now, let's focus on the rest of this declaration. An enumeration begins with the keyword Enum, which is generally followed by an identifier, such as:
Enum Temperatures
The base-type is the underlying type for the enumeration. 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., Short, Long). For example, the following fragment declares an enumeration of Longs:
Enum ServingSizes As Long Small = 1 Regular = 2 Large = 3 End Enum
Example 3-3 rewrites Example 3-2 to use an enumeration.
Option Strict On Imports System Module Module1 Enum Temperatures CelsiusMeetsFahrenheit = -40 WickedCold = 0 FreezingPoint = 32 LightJacketWeather = 60 SwimmingWeather = 72 BoilingPoint = 212 End Enum 'Temperatures Sub Main( ) Console.WriteLine("Freezing point of water: {0}", _ CType(Temperatures.FreezingPoint, Integer)) Console.WriteLine("Boiling point of water: {0}", _ CType(Temperatures.BoilingPoint, Integer)) End Sub End Module
In this example, the EnumType of each of the enumerated values is Temperatures. As you can see, an Enum (e.g., WickedCold) must be qualified by its Enumtype (e.g., Temperatures.WickedCold). This was optional in VB6, but it is mandated in VB.NET.
When you want to display the value of an enumerated constant, rather than its name, you must cast the constant to its underlying type (Integer). The Integer value is passed to WriteLine( ), and that value is displayed.
Each constant in an enumeration corresponds to a numerical value; in this case, an Integer. If you don't specifically set it otherwise, the enumeration begins at 0 and each subsequent value counts up from the previous.
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.
|
It is nearly impossible to write a Visual Basic .NET 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"
Strings will be covered in much greater detail in Chapter 10.
Top |