Working with Specific Data Types
The String data type is useful for managing text in your programs, but what about numbers, dates, and other types of information? To allow for the efficient memory management of all types of data, Visual Basic provides several additional data types that you can use for your variables. Many of these are familiar data types from earlier versions of BASIC or Visual Basic, and some of the data types are new or have been changed in Visual Studio 2005 to allow for the efficient processing of data in newer 64-bit computers.
The following table lists the fundamental (or elementary) data types in Visual Basic. Expe-rienced programmers will notice four new data types in Visual Basic 2005: SByte, UShort, UInteger, and ULong. SByte allows for “signed” byte values—that is, for both positive and negative numbers. UShort, UInteger, and ULong are “unsigned” data types—meaning that they cannot hold negative numbers. (However, as unsigned data types they offer twice the positive-number range of their signed counterparts, as shown in the table below.) You'll gain a performance advantage in your programs if you choose the right data type for your variables—a size that's neither too big nor too small. In the next exercise, you'll see how several of these data types work.
NOTE
Variable storage size is measured in bits. The amount of space required to store one standard (ASCII) keyboard character in memory is 8 bits, which equals 1 byte.
Data type | Size | Range | Sample usage |
Short | 16-bit | -32,768 through 32,767 |
Dim Birds As Short Birds = 12500 |
UShort | 16-bit | 0 through 65,535 | |
Integer | 32-bit | -2,147,483,648 through 2,147,483,647 |
Dim Insects As Integer Insects = 37500000 |
UInteger | 32-bit | 0 through 4,294,967,295 |
Dim Joys As UInteger Joys = 3000000000 |
Long | 64-bit | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
Dim WorldPop As Long WorldPop = 4800000004 |
ULong | 64-bit | 0 through 18,446,744,073,709,551,615 |
Dim Stars As ULong Stars = _ 1800000000000000000 |
Single | 32-bit floating point | -3.4028235E38 through 3.4028235E38 |
Dim Price As Single Price = 899.99 |
Double | 64-bit floating point | -1.79769313486231E308 through 1.79769313486231E308 |
Dim Pi As Double Pi = 3.1415926535 |
Decimal | 128-bit | values up to +/-79,228 x 1024 |
Dim Debt As Decimal Debt = 7600300.50 |
Byte | 8-bit | 0 through 255 (no negative numbers) |
Dim RetKey As Byte RetKey = 13 |
SByte | 8-bit | -128 through 127 |
Dim NegVal As SByte NegVal = -20 |
Char | 16-bit | Any Unicode symbol in the range 0–65,535 |
Dim UnicodeChar As Char UnicodeChar = "Ä" |
String | Usually 16-bits per character | 0 to approximately 2 billion 16-bit Unicode characters |
Dim Dog As String Dog = "pointer" |
Boolean | 16-bit | True or False (during conversions, 0 is converted to False, other values to True) |
Dim Flag as Boolean Flag = True |
Date | 64-bit | January 1, 0001, through December 31, 9999 |
Dim Birthday as Date Birthday = #3/1/1963# |
Object | 32-bit | Any type can be stored in a variable of type Object |
Dim MyApp As Object MyApp = CreateObject _ ("Word.Application") |
Use fundamental data types in code
On the File menu, click Open Project.
The Open Project dialog box appears.
Open the Data Types project in the c:\vb05sbs\chap05\data types folder.
If the project's form isn't visible, click Form1.vb in Solution Explorer, and then click the View Designer button.
Data Types is a complete Visual Basic program that I created to demonstrate how the fundamental data types work. You'll run the program to see what the data types look like, and then you'll look at how the variables are declared and used in the program code. You'll also learn where to place variable declarations so that they're available to all the event procedures in your program.
Click the Start Debugging button on the Standard toolbar.
The following application window appears:
The Data Types program lets you experiment with 11 data types, including integer, single-precision floating point, and date. The program displays an example of each type when you click its name in the list box.
Click the Integer type in the list box.
The number 37,500,000 appears in the Sample Data box, as shown in the illustration on below. Note that with the Short, Integer, and Long data types, you can't insert or display commas. To display commas, you'll need to use the Format function.
Click the Date type in the list box.
The date 3/1/1963 appears in the Sample Data box.
Click each data type in the list box to see how Visual Basic displays it in the Sample Data box.
Click the Quit button to stop the program.
Now you'll examine how the fundamental data types are declared at the top of the form and how they're used in the ListBox1_SelectedIndexChanged event procedure.
Double-click the form itself (not any objects on the form), and enlarge the Code Editor to see more of the program code.
The Code Editor looks like this:
Scroll to the top of the Code Editor to see the dozen or so program statements I added to declare 11 variables in your program—one for each of the fundamental data types in Visual Basic. (I didn't create an example for the SByte, UShort, UInteger, and ULong types, because they closely resemble their signed or unsigned counterparts.) By placing each Dim statement here, at the top of the form's code initialization area, I'm ensuring that the variables will be valid, or will have scope, for all of the form's event procedures. That way, I can set the value of a variable in one event procedure and read it in another. Normally, variables are valid only in the event procedure in which they're declared. To make them valid across the form, you need to declare variables at the top of your form's code.
NOTE
I've given each variable the same name as I did in the data types table earlier in the chapter so that you can see the examples I showed you in actual program code.
Scroll down in the Code Editor, and examine the Form1_Load event procedure.
You'll see the following statements, which add items to the list box object in the program. (You might remember this syntax from Chapter 3, “Working with Toolbox Controls”—I used some similar statements there.)
Scroll down and examine the ListBox1_SelectedIndexChanged event procedure.
The ListBox1_SelectedIndexChanged event procedure processes the selections you make in the list box and looks like this:
The heart of the event procedure is a Select Case decision structure. In the next chapter, we'll discuss how this group of program statements selects one choice from many. For now, notice how each section of the Select Case block assigns a sample value to one of the fundamental data type variables and then assigns the variable to the Text property of the Label4 object on the form. I used code like this in Chapter 3 to process list box choices, and you can use these techniques to work with list boxes and data types in your own programs.
NOTE
If you have more than one form in your project, you need to declare variables in a slightly different way (and place) to give them scope throughout your program (that is, in each form that your project contains). The type of variable that you'll declare is a public, or global, variable, and it's declared in a module, a special file that contains declarations and procedures not associated with a particular form. For information about creating public variables in modules, see Chapter 10, “Creating Modules and Procedures.”
Scroll through the ListBox1_SelectedIndexChanged event procedure, and examine each of the variable assignments closely.
Try changing the data in a few of the variable assignment statements and running the program again to see what the data looks like. In particular, you might try assigning values to variables that are outside their accepted range, as shown in the data types table presented earlier. If you make such an error, Visual Basic adds a jagged underline below the incorrect value in the Code Editor, and the program won't run until you change it. To learn more about your mistake, you can hold the mouse pointer over the jagged underlined value and read a short ScreenTip error message about the problem.
If you made any changes you want to save to disk, click the Save All button on the Standard toolbar.
User-Defined Data Types
Visual Basic also lets you create your own data types. This feature is most useful when you're dealing with a group of data items that naturally fit together but fall into different data categories. You create a user-defined type (UDT) by using the Structure statement, and you declare variables associated with the new type by using the Dim statement. Be aware that the Structure statement cannot be located in an event procedure—it must be located at the top of the form along with other variable declarations, or in a code module.
For example, the following declaration creates a user-defined data type named Employee that can store the name, date of birth, and hire date associated with a worker:
Structure Employee Dim Name As String Dim DateOfBirth As Date Dim HireDate As Date End Structure
After you create a data type, you can use it in the program code for the form's or module's event procedures. The following statements use the new Employee type. The first statement creates a variable named ProductManager, of the Employee type, and the second statement assigns the name “Greg Baker” to the Name component of the variable:
Dim ProductManager As Employee ProductManager.Name = "Greg Baker"
This looks a little similar to setting a property, doesn't it? Visual Basic uses the same notation for the relationship between objects and properties as it uses for the relationship between user-defined data types and component variables.
Constants: Variables That Don't Change
If a variable in your program contains a value that never changes (such as π, a fixed mathe-matical entity), you might consider storing the value as a constant instead of as a variable. A constant is a meaningful name that takes the place of a number or a text string that doesn't change. Constants are useful because they increase the readability of program code, they can reduce programming mistakes, and they make global changes easier to accomplish later. Constants operate a lot like variables, but you can't modify their values at run time. They are declared with the Const keyword, as shown in the following example:
Const Pi As Double = 3.14159265
This statement creates a constant named Pi that can be used in place of the value of π in the program code. To make a constant available to all the objects and event procedures in your form, place the statement at the top of your form along with other variable and structure declarations that will have scope in all of the form's event procedures. To make the constant available to all the forms and modules in a program (not just Form1), create the constant in a code module, with the Public keyword in front of it. For example:
Public Const Pi As Double = 3.14159265
The following exercise demonstrates how you can use a constant in an event procedure.
Use a constant in an event procedure
On the File menu, click Open Project.
The Open Project dialog box appears.
Open the Constant Tester project in the c:\vb05sbs\chap05\constant tester folder.
If the project's form isn't visible, click Form1.vb in Solution Explorer, and then click the View Designer button.
The Constant Tester form appears in the Designer. Constant Tester is a skeleton program. The user interface is finished, but you need to type in the program code.
Double-click the Show Constant button on the form.
The Button1_Click event procedure appears in the Code Editor.
Type the following statements in the Button1_Click event procedure:
Const Pi As Double = 3.14159265 Label1.Text = Pi
TIP
The location you choose for your declarations should be based on how you plan to use the constants or the variables. Programmers typically keep the scope for declarations as small as possible, while still making them available for code that needs to use them. For example, if a constant is needed only in a single event procedure, you should put the constant declaration within that event procedure. However, you could also place the declaration at the top of the form's code, which would give all the event procedures in your form access to it.
Click the Start Debugging button on the Standard toolbar to run the program.
Click the Show Constant button.
The Pi constant appears in the label box, as shown here:
Click the Quit button to stop the program.
Constants are useful in program code, especially in involved mathematical formulas, such as Area = πr2. The next section describes how you can use operators and variables to write similar formulas.