WORKING WITH VARIABLES


Constants are great for storing data that does not change during program execution. However, most of the time, you will need to store data that may change as your application runs. In these situations, you will need to use variables to store the data.

A variable is a pointer or logical reference to a location in memory where a piece of data is stored. Therefore, a variable doesn't actually store the data, it only keeps track of where the data resides.

Variables provide your Visual Basic applications with the ability to process all kinds of data. For example, in previous chapter game projects, you have seen where applications have used text boxes to collect player input, which were then stored in variables and later processed.

image from book
DEFINITION

A variable stores data that may change during program execution.

image from book

There are two steps to working with variables, as listed below:

  • Variable declaration. This involves the naming of a variable and the identification of the type of data that it will store.

  • Variable assignment. This is the process of assigning a value to a variable.

Defining Variables

After working on the game projects in the first four chapters, you've probably figured out by now that one way to declare a variable is to use the Dim keyword, as demonstrated below.

 Dim intCounter 

The Dim keyword is used to reserve space in memory. In this example, I have declared a new variable named intCounter.A variable declared in this manner is considered to be loosely typed, meaning that because you did not tell Visual Basic what type of data it will store, Visual Basic has, by default, assigned the variable and data type of Object. As a general rule, it's a good idea to strongly type variables. This is done by adding the As keyword to the end of a Dim statement and then specifying a data type, as demonstrated below.

 Dim intCounter As Integer 

In this example, I declared a variable named intCounter indicating that it will be used to store an Integer. By specifying a data type, I also told Visual Basic how much memory will be required to store the intCounter variable. If you refer back to Table 5.1, you'll see that an Integer type variable requires 4 bytes of memory.

Trick 

Visual Basic provides a second way of declaring variables, known as implicit declaration. To implicitly declare a variable, all that you have to do is reference it as shown below, without previously declaring it.

 strPlayerName = "Alexander Ford" 

However, I strongly advise against implicitly declaring variables in your Visual Basic applications. Explicit variable declaration helps make your program code easier to read and is good programming practice.

If you wish, Visual Basic allows you to save space by declaring multiple variables of the same data type on a single line, as demonstrated below.

 Dim strFirstname, strMiddleName, strLastName As String 

Assigning Data to Variables

Once a variable has been declared, you can assign a value to it, as demonstrated below.

 Dim dteMyBirthday As Date dteMyBirthday = #November 20, 1964# 

If you don't assign a value to your variables when you first declare them, Visual Basic automatically assigns them a default value. A zero is automatically assigned to variables with a numeric data type. A empty string ("") is automatically assigned to a variable with a data type of String, and a date of January 1,0001 is automatically assigned to a variable with a data type of Date. Unless you want these default value assignments, you'll need to make sure that you remember to assign a value to your variables either when you first declare them or at least before the first time your application tries to use them.

To save space, you can also combine variable declaration and assignment into one statement, as demonstrated below.

 Dim dteMyBirthday As Date = #November 20, 1964# 

You can even declare and assign values to multiple variables in the same statement, as demonstrated below.

 Dim intMinimumAge As Integer = 16, intMaximumAge As Integer = 21 

You can also mix and match data types when declaring variables and making value assignments, as shown below.

 Dim strPlayerName As String = "Alexander Ford", intPlayerAge As Integer = 7 

Defining Local Variables

A local variable is one that is declared at the block or procedure level using the Dim keyword. Local variables can only be referenced within the block or procedure where they are defined and therefore are not accessible to other parts of a Visual Basic application.

image from book
DEFINITION

A block is a collection of statements that are processed as a unit. Blocks are created using the If statement and various looping statements.

image from book

For example, the following statements demonstrate how to declare and assign data to a local variable name blnGameOver within a block.

 If intCounter > 10 Then      Dim blnGameOver As Boolean      blnGameOver = True End If 

Because the blnGameOver variable is defined within a block, it cannot be referenced from anywhere outside the block. Similarly, the following example demonstrates how to declare and assign data to a local variable named strMessage within a procedure.

 Private Sub Button1_Click(ByVal sender As System.Object, _        ByVal e As System.EventArgs) Handles Button1.Click          Dim strMessage As String          strMessage = "Hello World!"          MessageBox.Show(strMessage) End Sub 

Local variables exist only while the block or procedure that declares them is executing. Once the block or procedure ends, Visual Basic destroys any local variables, freeing up the memory that they used. Thus, using local variables can help reduce the overall amount of memory used by your application when compared to static and module variables, which have a longer lifetime.

Defining Static Variables

A static variable is one that is declared at the block or procedure level using the Static keyword. Static variables can only be referenced within the block or procedure where they are defined and therefore cannot be accessed by other parts of a Visual Basic application. However, unlike local variables, a static variable continues to exist after the block or procedure that contains it has finished executing. In fact, a static variable exists as long as your application runs. The following example demonstrates how to use a static variable.

 Private Sub Button1_Click(ByVal sender As System.Object, _        ByVal e As System.EventArgs) Handles Button1.Click          Static intCounter As Integer          intCounter += 1 End Sub 

One good use for static variables is to create a procedure that behaves differently based on the number of times it has been executed. You can accomplish this by declaring a static variable with a data type of Integer, incrementing its value by 1 each time the procedure executes and adding programming logic for the procedure to behave differently when the value of the static variable reaches a certain number.

Defining Variable Scope

A module variable is one that is declared inside a module, structure, or class but that is not inside a procedure. Module variables are declared using the following syntax:

 Modifier VariableName As DataType 

The ability to reference a module variable depends on which of the following modifiers is used to define it:

  • Private. Accessible from within the module, structure, or class where it is declared

  • Public. Accessible from anywhere within the project where it is declared

  • Friend. Accessible from anywhere within the solution where it is defined

As an example, the following statements define a module variable name strMessage that can be accessed from anywhere within the Form1 class where it is defined. In this example, however, Form1 represents the form or window within the application. If the application consisted of more than one form and there was a need to be able to access the variable from either form, then you would need to use the Public or Friend keyword to redefine the variable's scope.

 Public Class Form1     Private strMessage As String = "Hello World!"     Private Sub Form1_Load(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles MyBase.Load         MessageBox.Show(strMessage)     End Sub End Class 

Trick 

As a general rule, it is considered to be a good programming practice to limit the scope of your variables as narrowly as possible. This helps conserve memory and reduces the chances of accidentally changing the value assigned to a variable from a location in a Visual Basic application.

Rules for Naming Variables

There are a few rules that you need to be aware of that govern the naming of variables. Failure to follow these rules, listed below, will result in an error.

  • Variable names must begin with either an alphabetic character or the underscore character.

  • Variable names cannot include spaces.

  • Variable names cannot be reserved words.

  • Variable names must be unique within their scope.

image from book
IN THE REAL WORLD

You have probably noticed already that I have been assigning descriptive variable names when declaring variables that help to identify their purpose or contents. This helps make program code easier to read and understand. You also may have noticed that I am preceding each variable name with a three-character prefix that helps to identify the type of data associated with the variable, making things easier to understand. I recommend that you follow a similar approach when naming your own variables. For your convenience, you may want to use the prefixes shown in the following List.

  • Boolean: bln

  • Byte: byt

  • Date: dtm

  • Double: dbl

  • Error: err

  • Integer: int

  • Long: lng

  • Object: obj

  • Single: sng

  • String: str

image from book

Recognizing Variables as Objects

As you may recall from Chapter 1, "An Introduction to Visual Basic 2005 Express," Visual Basic is an object-oriented programming language. The object-oriented programming design is so strongly integrated into Visual Basic that even variables are treated like objects. To see what I mean, perform the following exercise.

  1. Start Visual Basic and create a new Visual Basic application.

  2. Double-click on the default form (form1) to open the code editor and access the form's Load event procedure.

  3. By default, Visual Basic will generate the following code to set up the application's response to the Load event for you.

     Public Class Form1     Private Sub Form1_Load(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles MyBase.Load     End Sub End Class 

  4. Declare a variable name strUserAge as an Integer and assign it a value of 55 as shown below.

     Dim strUserAge As Integer = 55 

  5. Next, type the following partial statement exactly as shown below.

     MessageBox.Show(strUserAge. 

  6. Because Visual Basic treats variables as objects, IntelliSense kicks in and displays all of the properties and methods available, as shown in Figure 5.8.

  7. Click on ToString and press Enter. The statement should now look like the example shown below.

     MessageBox.Show(strUserAge.Tostring) 

    Trick 

    You can use the ToString method to return a string showing the value for the specified variable, whether it is a number or a date.

image from book
Figure 5.8: Using IntelliSense to view methods and properties associated with a variable object.

Variable Conversion

Data typing is important because it tells Visual Basic how to store and handle the value that you assign. If you don't specify a variable's data type, Visual Basic assigns the variable a data type of Object. Then, later in your application when your program makes a change to the variable, Visual Basic takes its best guess as to how to convert the variable's data type assignment based on the action being taken. Most of the time, Visual Basic selects a data type that works just fine. However, it may not select the most efficient data type. And sometimes, the data type it selects causes problems. For example, if you declare a variable as an Integer but then assign a number that includes a decimal point, such as 5.1, to it, Visual Basic automatically rounds 5.1 to 5, which can lead to all sorts of problems. Instead of Integer, a value type of Double would have been the right choice in this example.

Trick 

As with constants, Visual Basic gives you some control over the way that it identifies variable data types. If you assign a value of 10 to a variable, Visual Basic automatically interprets the value as a number. But if you enclose the value inside matching double quotation marks, Visual Basic treats it as a string. Likewise, matching pound signs (##) are used to identify dates.

As you develop new Visual Basic applications, you are going to come across times when you will have to convert data from one type to another. There are two ways to convert a value's data type. One is to let Visual Basic do it for you automatically. However, as the following example demonstrates, sometimes Visual Basic gets things wrong.

 Public Class Form1     Private Sub Form1_Load(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles MyBase.Load         Dim dblPI As Double = 3.14         Dim intPI As Integer         intPI = dblPI         MessageBox.Show(intPI)     End Sub End Class 

If you key in and run this example, you see that Visual Basic truncates .14, displaying a value of 3. This occurs because variables of the data type Integer are not able to store decimal information. Most likely, a conversion of this type will cause a problem in your applications. One way to prevent this type of problem is to add an Option Strict On statement to your program, as demonstrated below.

 Option Strict On Public Class Form1     Private Sub Form1_Load(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles MyBase.Load         Dim dblPI As Double = 3.14         Dim intPI As Integer         intPI = dblPI         MessageBox.Show(intPI)     End Sub End Class 

Trap 

Take note of the Location of the Option Strict On statement. Visual Basic requires that you place it before any declaration statements; therefore, it had to go before the Public Class Form1 statement. If you put it anywhere else in this example, you'll get an error.

Now, with the Option Strict On statement in place, press F5, and you see that Visual Basic displays a message indicating that an error has been detected. Visual Basic automatically displays the error message in the Error List window, as demonstrated in Figure 5.9.

image from book
Figure 5.9: Adding Option Strict On forces Visual Basic to alert you to variable conversion problems.

The first error displayed in the Error List window states that conversion from Double to Integer was disallowed. The following statement generated this conversion error when the example attempted to convert the value of pi from a data type of Double to a data type of Integer.

 intPI = dblPI 

The second error states that conversion from Integer to String was disallowed,: as well. The following statement generated this conversion error, because the MessageBox.Show method can only display data of the String type.

 MessageBox.Show(intPI) 

Fortunately, Visual Basic supplies you with a large number of conversion methods and functions allowing you to tell it how you want to convert data from one type to another. To use the methods and functions, you must specify the data to be converted inside the opening and closing parentheses, as demonstrated in the following example.

 Option Strict On Public Class Form1     Private Sub Form1_Load(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles MyBase.Load         Dim dblPI As Double = 3.14         Dim intPI As Integer         intPI = CInt(dblPI)         MessageBox.Show(Convert.ToString(intPI))     End Sub End Class 

In this example, it is assumed that the truncation of .14 is acceptable. Therefore the value stored as a Double in the dblPI variable is converted to an Integer data type using the Cint() function. The Convert.ToString() method is used to convert the Integer data type associated with the intPI variable to a String so that it can be displayed by the MessageBox.Show method.

Functions and Methods for Manipulating Strings

A variable with a data type of String can be used to store up to 2 million characters. One of the many strengths of Visual Basic is the abundance of string manipulating functions and methods that it provides. In fact, Visual Basic provides so many different ways of manipulating strings that it is unlikely you will ever have to develop your own custom string handling functions.

In previous chapters, you have seen a number of examples of how to work with strings using the ampersand (&) operator, which joins or concatenates two strings together. Visual Basic provides a number of other string manipulation tools, including the properties and methods listed in Table 5.3.

Table 5.3: String Handling Properties and Methods

String Object Methods

Description

String.ToLower

This method converts a string to all lowercase

String.ToUpper

This method converts a string to all uppercase

String. Length

This property is used to retrieve the length of a string

String.SubString

This method extracts a portion of a string

String.ConCat

This method combines two strings

String.Chars

This property is used to search for one string within another string

String.TrimStart

This method removes leading blank spaces from the left side of a string

String.TimeEnd

This method removes trailing blank spaces from the right side of a string

image from book
DEFINITION

A string is a series of one or more characters, which may include alphabetic, numeric, and special characters, as well as spaces, that is defined by enclosing the characters within a pair of double quotation marks ("").

image from book

As a quick example of how to use these functions and methods, take a look at the following example.

 Public Class Form1     Private Sub Form1_Load(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles MyBase.Load        Dim strMsg As String = "Once upon a time in a far away land."        MessageBox.Show("String is " & strMsg.Length & " characters long.")     End Sub End Class 

In this example, the Length property is used to display the number of characters that makes up the strMsg variable's value.




Microsoft Visual Basic 2005 Express Edition Programming for the Absolute Beginner
Microsoft Visual Basic 2005 Express Edition Programming for the Absolute Beginner
ISBN: 1592008143
EAN: 2147483647
Year: 2006
Pages: 126

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