Like any programming language, Visual Basic requires the ability to store data and then later to retrieve and process it. You've seen numerous examples of this in game projects from earlier chapters. In this chapter, I'll explain your options for storing and retrieving data in Visual Basic.
Data is information collected by your application that it stores, retrieves, and modifies during execution.
Visual Basic is an extremely flexible programming language, often offering you many different ways of performing a particular task. Such is the case when it comes to working with data. In fact, Visual Basic provides a number of different data management options, each of which is uniquely suited to different situations. The options that you decide to use will vary from situation to situation, because the best method for storing data varies based on the manner in which the data is used.
Constants. There will be times when you develop applications that need to work with known values that do not change during the execution of the applications. A good example would be an application that performs various mathematical calculations, using known values such as pi. Because the value of pi does not change, you can assign it to a constant.
Variables. Constants are fine for storing limited amounts of data. However, in most cases, the data that your applications process will change during program execution. In these situations, you will need to use variables to store the data.
Arrays. Sometimes, you may find that you need to store and work with collections of related information, such as a list of user names. In these situations, you can load the entire list into an array, which is an indexed list of related information.
Structures. A structure is a user-defined data type that allows you to group together related variables into a single entity. For example, if you were creating an application that needed to work with people's names, addresses, and phone numbers, you could define a structure containing variables representing each of these pieces of information. Then, later in your application, you could create an array based on that structure and use it to store and process all three pieces of data for each person at the same time.
Trick | Another option that is available to you for managing data is to define your own customized Class. This option is covered later in Chapter 9, "Getting Comfortable with Object-Oriented Programming." |
Visual Basic is capable of storing and working with many different data types. Table 5.1 lists each of the data types supported by Visual Basic.
Data Type | Storage Requirements (in Bytes) | Value Range |
---|---|---|
Boolean | 2 | True or False |
Byte | 1 | 0 to 255 |
Char | 2 | 0 to 65535 |
Date | 8 | January 1,0001 to December 31, 9999 |
Decimal | 16 | 0 to +/- 79,228,162,514,264,337,593,543,950,335 |
Double | 8 | -1.79769313486231570E+308 to - 4.94065645841246544E-324 for negative number and 4.94065645841246544E-324 to 1.79769313486231570E+308 for positive numbers |
Integer | 4 | -2,147,483,648 to 2,147,483,647 |
Long | 8 | -2,147,483,648 to 2,147,483,647 |
Object | 4 | Any type of variable |
Sbyte | 1 | -128 to 127 |
Short | 2 | -32,768 to 32,767 |
Single | 4 | -3.402823E+38 to -1.401298E-45 for negative numbers and 1.401298E-45 and 3.4028235E+E38 for positive numbers |
String | Varies | Up to two billion characters |
Ulnteger | 4 | 0 to 4,294,967,295 |
Ulong | 8 | 0 to 18,446,744,073,709,551,615 |
UShort | 2 | 0 to 65,535 |
As Table 5.1 shows, Visual Basic supports a large collection of data types. Each data type, except the object data type, is capable of storing a specific type of data. As Table 5.1 also shows, the amount of memory required to store data varies based on its data type. Visual Basic is very flexible. If you don't tell Visual Basic what the data type is for a particular piece of data, it assigns the data a default data type of Object.
Trap | Although convenient, using the Object data type is not the most efficient option and will cause your application to consume additional memory. Although a variable with a data type of Object can store any type of value, it cannot do so as efficiently as a variable that has been assigned the correct data type. Therefore, I strongly recommend that you always specify the data type for your variables. Just make sure when you do so that you specify a data type that accurately matches the type of data to be stored and that is capable of handling the size of the data to be stored. |
Trick | When you specify the correct data types, you set up your Visual Basic programs to run faster by reducing the amount of memory used by the application and by eliminating the need to later convert data from one data type to another. However, I wouldn't invest too much time in analyzing the optimum data type for every variable that you ever need to create. In most cases, you can strike a good balance between program efficiency and memory usage versus your development time by using String, Integer, Double, Boolean, and Date. |
By specifying a data type, you tell Visual Basic what range of values are allowable for a variable as well as what actions can be performed on the variable. For example, by specifying one of the numeric data types, you tell Visual Basic that it can perform mathematic calculations using the variable.
When deciding whether to use a constant, variable, array, or structure to store a piece of data, it is best to first look at how the data is to be used. Data that is known at design time and that will not change during the execution of the application should be defined as a constant, allowing Visual Basic to more efficiently store and process the data.
Within Visual Basic, there are two sources of constants. You can define your own constants and assign data to them, or Visual Basic makes available to you a number of predefined constants.
By assigning data to a constant instead of to a variable, you eliminate the possibility that you might accidentally change the data later on in your application, which can happen in cases where you declare two very similarly named variables. If you try to change the data assigned to a constant, Visual Basic will flag it as an error when you test the execution of your application.
Constants make your application code easier to read. Your applications will also run faster because constants require less memory than variables.
To declare a constant within Visual Basic, you must use the Const keyword using the syntax outlined below.
Const ConstName As DataType = Expression
ConstName represents the name that you assign to the constant. DataType identifies the type of data that will be assigned to the constant, and Expression represents the value that is being assigned. To demonstrate how constants work, take a look at the following example:
Public Class Form1 Const cTitleBarMsg As String = "The Story of Mighty Molly" Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load MessageBox.Show("Mighty Molly was the bravest of ......", _ cTitleBarMsg) End Sub End Class
In this example, a constant named cTitleBarMsg is declared with a date type of String and is assigned a value of "The Story of Mighty Molly". It is declared outside of any procedure and therefore can be accessed from anywhere within the Public Class Forml and End Class statements. This is demonstrated when the MessageBox.Show method uses it as an argument specifying the pop-up window's title bar message, as shown in Figure 5.6.
Figure 5.6: By assigning a string to a constant, you can use it throughout your application to specify a title bar message in all pop-up windows.
Trick | As you may have noticed in the previous example, I added the letter c to the beginning of the constant name to help identify the constant. I recommend this same naming convention for your constants. It will help make your constants stand out and make your code easier to read. |
Trap | When assigning data to constants or variables, it is important that you package it appropriately. The following example demonstrates how to define a constant for a numeric type value:
Const cMaxValue As Integer = 999 To assign a String data type value to a constant, you must enclose the string within a pair of matching quotation marks, as shown below.
Const cCompanyname = "Inner IV Enterprises, Inc." Finally, to assign a Date data type value to a constant, you must enclose the string within a pair of matching pound signs, as shown below.
Const cBirthday = #November 20, 1964# |
Visual Basic provides you with access to all sorts of predefined constants. For example, in Chapter 3, "Creating an Application Interface," you learned how to work with constants that specified what types of buttons and icons should appear in pop-up windows displayed by the MessageBox.Show method. Another example that you have seen of using Visual Basic built-in constants was in Chapter 4, "Working with Menus and Toolbars," where constants were used to format the output of text display by the Lottery Assistant game.
Table 5.2 lists a number of Visual Basic constants that you are likely to use over time to control the output of text strings.
Constant | Description |
---|---|
ControlCharsCr | Executes a carriage return |
ControlCharsCrLf | Executes a carriage return and a line feed |
ControlCharsFormFeed | Executes a form feed |
ControlCharsLf | Executes a line feed |
ControlCharsNewLine | Adds a newline character |
ControlCharsTab | Executes a horizontal tab |
You can see some of these string constants in action in the following example.
Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load Dim strStoryMsg As String = "" strStoryMsg &= "Once it was believed that the world was flat." strStoryMsg &= ControlChars.NewLine & "Later, it was found " strStoryMsg &= "that the world was round." & ControlChars.NewLine strStoryMsg &= "Who knew?" & ControlChars.NewLine strStoryMsg &= ControlChars.NewLine & ControlChars.Tab & MessageBox.Show(strStoryMsg) End Sub
As you can see, the ControlCharsNewLine and ControlCharsTab constants were embedded within the string text in order to control when line breaks occurred and to execute a tab operation. When executed, the example displays the pop-up window shown in Figure 5.7.
Figure 5.7: Using string constants to specify the output format of a string.