Writing Code with Visual Basic .NET
Introduction
Now that you've become more familiar with the Visual Basic .NET development environment, it's time to begin writing code. Although Visual Basic .NET makes it easy to write a simple program without using much code, any program simpler than a demo will need to keep track of information, and do simple calculations and similar tasks. To write code that performs these tasks, you'll need a good understanding of variables. By understanding the use and types of variables, you're creating the foundation for your understanding of Visual Basic .NET. Similarly, just as when you began learning simple arithmetic, you will need to learn some of the simple operators that can be used to work with number and string variables in your programs. Today, you will learn
-
The types of variables you can create with Visual Basic .NET
-
Some simple operators and functions available in Visual Basic .NET
-
The fundamentals of writing code in Visual Basic .NET, including how to write procedures
Variables and Assignment
Variables and assignment are at the core of every programming language. Variables enable you to store information for later use, and assignment is the way you get information into variables.
What Is a Variable?
A variable is a bucket. It's a place to hold information until you need it. You will use variables throughout your programs to hold temporary values during calculations, to store user input, and to prepare information that will be later displayed to users.
Available Variable Types
Just as with pants, one size does not fit all variables. Although it is possible to create and use a variable that is capable of holding anything, it's not always the best solution. It's easy to imagine that a variable holding strings must do something different from a variable designed to hold numbers. In addition, even different types of numbers require different variable types. Some numbers, such as 1 or 5280, don't have a decimal place, whereas 3.14159265358979 and 16.50 do. A variable made to hold a number with a decimal must do something specifically to keep track of the values after the decimal. Of course, that means that decimal numbers probably take up more memory. Any time a computer or program does more work, it usually needs more memory. So, it is important to keep in mind not only the type of information you need to store, but also the amount of memory the computer will have to manipulate to keep track of the variable.
There are three broad types of variables you can create with Visual Basic .NET. The first set encompasses variables that hold simple values, such as numbers or strings. There are many of these, each designed to hold values of various sizes. The second category is complex variables, which hold some combination of simple variables, and include arrays and user-defined types. Arrays are variables that hold a series of other variables, and user-defined types enable a user to create new types of variables. The third category of variables is object variables.
User-defined types (also known as structures) and object variables will be covered later, on Day 7, "Working with Objects." Today's discussion of variables will focus on simple variables and arrays.
Simple Variables
As described previously, the simple variable types "hold" values such as numbers and words. So, you might think that there only needs to be two types of variables: numbers and words. However, there are actually a number of different simple variable typeseach made to hold different sizes or kinds of numbers or strings.
Try to use the best variable type for the situation. Sometimes, you only need to keep track of a small numberfor example, if you're keeping track of the months of the year. Other times, you need to work with big numbers with many decimal placesfor example, if you're writing a program that performs engineering or scientific calculations.
The simple variables can be divided into four subgroups. The first, and largest, group is for integers, numbers that have no decimal places. The second group is used for numbers that have decimal places. Strings and characters make up the third group, and the fourth group is best described as "other." Let's look at each of these groups and see when it is appropriate to use each.
Integer Variables
The integer variables hold the familiar whole numbers (that is, numbers without decimal places). Integers are one of the most common variables you will use in programs, and the easiest for computers to deal with. Because of this ease, they should be your first choice as a variable type when you need to work with numbers. Table 3.1 shows a number of different integer variables, each designed to hold numbers of different sizes, and use different amounts of memory. The amount of memory used is measured in bytes. (One byte contains eight bits, which is just a fancy way of saying that each byte has eight 1's or 0's, or a combination of 1's and 0's.) Although there is no harm in using a variable designed to hold larger values than needed, it wastes memory. In addition, it could cause your program to run slower because it would have to keep track of larger sections of memory, even when that memory is never used.
Table 3.1 Integer Variable Types
Data Type |
Size (Bytes) |
Range |
Comments |
Byte |
1 |
0 to 255 |
Rather small, and unlike the other integer data types, the Byte does not support negative numbers. This is because the Byte represents the value that the computer actually stores for each byte in memory. In order to store negative numbers, the computer uses part of each byte to hold the "negative" part. This is useful when keeping track of small numbers that are never negative, such as days in a month, or months in a year. |
Short |
2 |
32,768 to32,767 |
A handy, small integer variable. You can use a Short whenever you don't need the full range of an Integer, for example, if you were writing a program to count the number of employees of a company that only had a few thousand employees. |
Integer |
4 |
2,147,483,648 to 2,147,483,647 |
The standard integer variable. For the most part, the Integer is the fastest type of variable to use, as it requires the computer to do the least amount of work. One use for a variable of this type would be to track the number of sheep in New Zealand (approximately 47,394,000 in 1997). |
Long |
8 |
9,223,372,036, 854,775,808 9,223,372,036, 854,775,807 |
The perfect variable type for those times when you are working with really, really big numbers (that's 9 quintillion to +9 quintillion, or ±9 x 1018, for those keeping track). A Long would be useful if you were tracking the number of stars in the universe (estimated to be about 1022). |
Numbers with Decimal Places
A lot of number crunching is done without decimal places. However, more calculations, especially in engineering, finance, and science, require that you also keep a decimal value. Table 3.2 describes the two main decimal variable types. Deciding which to use depends on the degree of accuracy you need to track, rather than the size of values, because they all can hold rather large numbers. In case you don't remember scientific notation from school, the superscript number above the 10 is the number of times you need to multiply by 10 (if positive) or divide by 10 (if negative). Therefore 106 is 10 six times, or 1,000,000, and 10-6 is 0.000001.
Table 3.2 Decimal Variable Types
Data Type |
Size (Bytes) |
Range |
Comments |
Single |
4 |
3.402823 x 1038 to 1.401298 x 1045 for negative numbers; 1.401298 x 1045 to 3.402823 x 1038 for positive numbers |
Don't worry too much about the size of those numbers in the range. The Single can keep track of very large (or very small) numbers. The important measure for a Single is accuracy. The name Single denotes that this variable type is for single-precision floating point numbers. That's computer-speak meaning: "It's really only good at holding seven important digits." Look at each of the numbers in the range. Notice that each of them has a number before the decimal place, and six following it, plus the exponent (the number above the 10). So, although the Single is good at storing both large and small numbers, it's not as accurate as the others, and could cause rounding errors if you do a lot of calculations with really large, or really small, numbers. The Single variable type would be useful in a program where less accuracy is needed. |
Double |
8 |
1.79769313486231 x 10308 to 4.94065645841247 x 10324 for negative numbers; 4.94065645841247 x 10324 to 1.79769313486232 x 10308 for positive numbers |
The Double is a "double-precision floating point" variable, so it holds twice as many significant digits as the Single, or 15 decimal places. Use a Double whenever you are doing calculations with large numbers, or when you want to avoid the rounding errors that can happen with the Single, such as when doing calculations in engineering or scientific applications. |
Strings and Characters
Numbers are fine if you need to track quantities or time, but you also need to deal with words frequently in programming. Visual Basic .NET gives you variables for storing strings: the Char and the String. The Char is good for storing only a single character (thus the name), whereas the String can hold strings of great length. Table 3.3 describes the two data types in more detail.
Table 3.3 String Variable Types
Data Type |
Size (bytes) |
Range |
Comments |
Char |
2 |
One character |
Good for holding a single character. |
String |
10 + 2 per character |
Up to 2 billion characters |
Use a String to hold that novel you always wanted to write. If you assume five characters on average per word, and 250 words per page, a single String variable can hold 1.7 million pages of text. |
Why does each Char and each character in a String take up two bytes? After all, there are only 26 characters used in English, plus numbers and symbolssurely, you don't need two bytes (65,536 possible values). You wouldn't if every language used the same character set.
That scenario is what the formerly popular ASCII (or ANSI) character set defined. In ASCII, one byte equals one character, and every computer that used ASCII always positioned the same characters at the same position in the list. So the ASCII value 65 was always the letter "A," and the symbol "@" was had the value 64. If you wanted to do the same for all the other symbols people use in writing, however, you needed more characters. To accommodate this, a new system was developed, called Unicode.
With Unicode, each character is represented as two bytes. This allows for the storage of all the characters in the ASCII chart, as well as characters for Russian, Greek, Japanese and Thai languages, for mathematics, and so on. In Unicode, 65 still represents the letter "A", but 8800 is the character for . The Japanese Hiragana character "No," is represented as character 12398. Visual Basic .NET uses the Unicode values for all characters, so the Char uses two bytes, and each character in a String adds two bytes of additional storage space.
Other Simple Variable Types
It never fails when you try to categorize things. Something always defies being categorized (just imagine the first zoologist to come upon the platypus). Likewise, there are some variables that don't fit neatly into the previously described categories. In Visual Basic .NET, there are two such "other" variable types, the Boolean, and the Date. They are described in more detail in Table 3.4.
Table 3.4 Other Simple Variable Types
Data Type |
Size (Bytes) |
Range |
Comments |
Boolean |
2 |
True or False |
So, if it's just holding a True or False, why is it two bytes? Visual Basic has traditionally used 0 and 1 for False and True. Defining these two values requires two bytes. |
Date |
8 |
January 1, 100 to December 31, 9999 |
The Date variable is capable of holding most dates you will deal with (unless you're a historian or geologist). It also is aware of all the rules for dates (such as adding a day in leap years), so if you add 1 to the Date variable value of "February 28, 2000," you will get "February 29, 2000," but if you do the same for "February 28, 2001," you will get "March 1, 2001." The only real limitation of the Date variable is its size. |
NOTE
You could use another data type to store dates such as a String, or an Integer representing the number of days after some specific date, but why bother? We all know the problems that can lead to (especially after enjoying all the power outages, nuclear plant explosions and other failures on January 1, 2000).
Declaring Variables
Now that you know the types of variables available, how do you create them in your programs? The simplest way is with the Dim (short for "Dimension") keyword, followed by the name of the variable, the keyword As, and finally the type of the variable. It looks like
Dim iSomeNumber As Integer
This would create the new variable iSomeNumber, which takes up four bytes and can hold a number as large as +/ 2 billion. Here are some more possible variable declarations:
Dim sFirstName As String Dim dblGrossDomesticProduct As Double Dim bLearned As Boolean
One new feature in Visual Basic .NET is the capability to give a value to a variable as you are creating it. You simply assign a value to the new variable on the same line as the Dim statement:
Dim dtDateOfMagnaCartaSigning As Date = #June 15, 1215# Dim lPeopleOnEarth As Long = 6000000000
We'll look at some other ways of declaring variables later, when we discuss scope.
Arrays
A variable's capability to hold one of anything is handy, even essential, in programming. However, you might need to store a number of related items. For example, if you were writing a program to play chess, the squares on the board would need to be represented as a collection of related items. You use arrays to create variables that will store all the related items together. For the chess program, you would likely store the chessboard as an array of positions, each position holding the type of chess piece (or none) at that position. If you did not use an array variable, you would have to use 64 separate variables. You might also need to track a list of strings, for example, a list of the names of students in a class. Whenever you need to store a list of items, you use an array.
As with declaring simple variables, you declare an array with the Dim keyword. However, there are some differences between simple variable declarations and array declarations because arrays are collections of variables. Listing 3.1 shows three possible ways of declaring arrays.
Listing 3.1 Declaring Arrays
1 'Simple declaration 2 Dim iValues(3) As Integer 3 Dim dtDates() As Date 4 Dim I As Integer 5 For I = 1 To 3 6 iValues(I-1) = I 7 Next 8 'Changing the size of an existing array 9 ReDim dtDates(4) 10 'fill the list of dates 11 dtDates(0)="6/15/1215" 'Signing of Magna Carta 12 dtDates(1)="8/28/1962" 'Martin Luther King Jr. delivers "I have a dream" 13 dtDates(2)="7/20/1969" 'Apollo 11 lands on Moon 14 dtDates(3)="2/14/1946" 'ENIAC unveiled to public 15 'Declaration with Initialization 16 Dim sMonths() As String = {"Jan","Feb","Mar","Apr","May","Jun", _ 17 "Jul","Aug","Sep","Oct","Nov","Dec"} 18 'Using arrays 19 Console.WriteLine("") 20 Console.WriteLine("Second value in iValues = {0}", iValues(1)) 21 Console.WriteLine("Third date in dtDates = {0}", dtDates(2)) 22 Console.WriteLine("Eleventh month of the year = {0}", sMonths(10))
In the first example, iValues is declared as a three-member array. Each item in the array is an Integer. That much should make sense. The potentially confusing part is in the way you refer to each member of the array. This is shown in the For...Next loop beginning at lines 5 through 7 (Note that we will be covering the For...Next loop tomorrow). Notice that the three members of the array are actually numbered beginning with 0 and going up to 2. Therefore, the second member of the array is at position 1, not 2.
NOTE
It's worth noting that computers, unlike people, always prefer to begin counting at zero. The overall reasons are best left in the recesses of their tiny silicon minds, but we should be aware of this, especially around arrays.
The second array created, the months of the year, is declared and initialized. Just as you can initialize simple variables as you declare them, you can do the same with arrays. In the case of arrays, however, you put each of the elements of the array in a comma-delimited list, wrapped in braces (curly brackets), as shown on line 16. This creates a 12-member array, with each element holding a string. Remember, however, that if you wanted to refer to each element, they are numbered from 0 to 11so sMonths(10) would be "Nov", not "Oct".
The final declaration is of a dynamically sized array. This array can be resized later to the correct size with the ReDim keyword as shown on line 10. Just as with the other array types, the items of the dynamic array are numbered from 0 to I minus 1. After the array is sized, you can then use it as any other array. This form of declaration is useful if the size of the array depends on the value of another variable, so that it wouldn't be known until runtime.
CAUTION
I have repeated the fact that all arrays begin with 0 in Visual Basic .NET because, previously, Visual Basic might not have operated that way. In versions of Visual Basic before Visual Basic .NET, you could use the Option Base 1 declaration at the beginning of a module to ensure that all arrays created in that module begin with 1. Alternatively, when declaring arrays, you could define the starting and ending array members, as shown in the following declaration. Neither of these options is available with Visual Basic .NET arrays.
Therefore, the following line of code is not valid in Visual Basic .NET:
Dim sngValues(15 To 51) As Single
Assignment
Assignment has been simplified in Visual Basic .NET. Earlier Visual Basic versions (Visual Basic 4.0 to 6.0) had two different ways of assigning a value to a variableone for simple variables (including structures and arrays) and one for object variables. Fortunately, the developers of Visual Basic .NET decided to remove the assignment method used for object variables, and rely only on the method used for simple variables. You assign values to variables (either simple or object) by putting the variable left of an equal sign, as shown in the following code:
iSomeVar = 1234 oObjectVar = New Something()
NOTE
In Visual Basic version 4.0 to version 6.0, the assignment lines shown previously would have appeared like this
iSomeVar = 1234 Set oObjectVar = New Something
However, the rules of when to use Set were confusing, so Microsoft removed the need for the Set keyword.
Constants
Constants are another class of values that you can use in your Visual Basic .NET programs. Constants are values that do not change, either for the lifetime of your program, or ever. For example, the months in a year, the value of pi, and the database server from which your program retrieves data are all constant values. You can define a value as being constant when you declare it. Any attempts to change the value of a constant will be marked as an error while you are still in the IDE (Integrated Development Environment), and before you attempt to run the application. Constants are declared using one of the two forms shown in the following code:
Const PI = 3.1415 As Double Const DSN As String = "Random"
If the type of the constant is not described in a declaration, the compiler must use the value type that best fits. However, it does not always select the best possible type. Generally, when declaring constants, if you do not include the type of the value, Visual Basic .NET will create the following variable types
Long For any undeclared whole numbers.
Double For any undeclared decimal numbers. Note: If the value is actually too large for a Double, it will be truncated.
String For any character values.
NOTE
Declare the type you want when declaring constants, just as you do when declaring variables.