In the first article in this series, you set up everything you need to begin programming with the Visual Basic .NET language. You even created, compiled, and ran you first program. In this article, you are going to begin exploring the Visual Basic .NET language with variables and data types.
The first program you created looked like this:
Imports System Module HelloWorld Public Sub Main() Console.WriteLine("Hello, World!") End Sub End Module
In the last article, I just had you type this program in blindly, compile, it and run it. Now, I’d like to go over this program line by line and explain what’s going on here.
The first line begins with the word Imports. The .NET Framework includes a vast library of pre-written code that you can use in your own applications. This code does a lot of the common tasks programmers need to do. So, by including it in a library, you don’t have to write the code yourself again and again—you can just use the code that’s provided in the library. The Imports statement tells the computer that you want to use a part of that library. In this case, you want to use the section of the library called System.
The next line begins with the word Module. A module is simply a place where you can write part or all of your application. All code has to be in some sort of module and an application can consist of one or more modules. The name of the module follows the word Module on the line. In this case, I named the module HelloWorld.
The next line begins with Public Sub and it defines a subroutine. A subroutine is a finer division of your code than a module. Each module can have many subroutines. Modules can help organize subroutines into sensible categories. The name of the subroutine in this program is Main. The empty parentheses after the word Main are necessary—you’ll explore that later.
Finally, you come to the meat of this program, such as it is: the code that displays the Hello, World! message. Console is an object that is inside the System library. (That’s why you had to use Import Library up at the top.) An object is like a module—it is a place where subroutines can be stored. To call a subroutine within the object, you separate the name of the object from the subroutine name by a period. So, in this code, I’m calling the WriteLine subroutine, which is inside the Console object. As I call it, I’m providing the text that I want to write inside parentheses after the subroutine name. The subroutine then takes that text and puts it on the screen—as you saw.
Almost all of the examples in this article series will use a structure much like the one in this example to demonstrate the features of Visual Basic .NET.
Creating and Using Variables
Think of variables as named boxes that you use to hold information temporarily so you can use it later. After you create a variable, you can put information inside it and then use the variable anywhere you’d normally use that information. Variables are very handy in all kinds of situations. For example, you can use one to store the result of a calculation until you have a chance to show it to the user.
Making your own variables
In VB.NET, you create (or declare) a new variable by using the Dim statement.
Create a new file and type in the following listing exactly as it appears here, and then use the process I describe in the first article to test it.
Imports System Module ShowTotal Public Sub Main() Dim Cost, Tax, Total As Integer Cost = 40 Tax = 2 Total = Cost + Tax Console.WriteLine("Total:") Console.WriteLine(Total) End Sub End Module
The line of code that begins with Dim creates three variables named Cost, Tax, and Total. You can give the variables any name you want, but choose names that will remind you of what they hold.
All three variables are identified As Integers, which means they can hold whole numbers. (I’ll discuss data types later in this article.) After they are created, Cost and Tax are immediately assigned values of 40 and 2, respectively. Then, the values held by Cost and Tax are added, and the sum is placed in the variable Total. Simple enough.
You can do this kind of math with any combination of numbers and variables. You use the normal + and – signs for addition and subtraction, respectively. Multiplication uses the * symbol, and division uses the / symbol. Exponents are created using the ^ symbol.
What happens when you run it?
Notice the two lines that display the information:
The first line is very similar to the line in your Hello, World! application. There is text that appears inside of quotation marks. This text is displayed on the screen exactly as it appears (minus the quotes). The second line doesn’t have any text in quotes. Instead, it has the variable Total, without quotes. This indicates that the value that the variable holds should be displayed.
Data types and numbers
Here’s a snippet of code from the program in the last section:
Dim Cost, Tax, Total As Integer
As I explained, you use Dim to create variables and this line identifies three new variables as integers. So, these variables have an integer data type.
If you think of a variable as a box for holding data, you can imagine that different boxes have different sizes and shapes. A box’s size and shape determine what the box can hold. This “size and shape” is analogous to a variable’s data type—that is, the type of data the variable can contain. Just as you can’t put a pair of shoes in a matchbox, you shouldn’t try to store someone’s last name in a variable that’s supposed to store a number.
A variable declared as an Integer, as these three are, can contain whole numbers (that is, numbers without a decimal point). You also can create variables to hold other types of numbers—for example:
Dim Pi As Single Pi = 3.14159
Variables with the data type Single can hold what are called single-precision values. That’s a confusing way of saying that a Single can hold a number that has a decimal point and digits after the decimal.
Where does the term single-precision come from? Well, it refers to the fact that variables of this type can hold numbers with a decimal point, but some numbers are too small for it to keep track of accurately. As you might expect, you also can declare double-precision variables, which use the Double data type. Double variables can hold very, very small numbers accurately. But, really, unless you are doing seriously complex scientific calculations, you probably can get by with the Single data type.
So, now you know what data type to use for a variable to hold almost any number you want. If it’s a whole number, use Integer. If it includes a decimal point, use Single.
Storing text in strings
In addition to holding numbers, variables can hold strings. A string is a bunch of letters put together to form words or sentences. Here’s an example:
Imports System Module HelloWorld Public Sub Main() Dim FirstName, LastName, WholeName As String FirstName = "Bill" LastName = "Gates" WholeName = FirstName & LastName Console.WriteLine(WholeName) End Sub End Module
Strings are always enclosed by quotation marks so you know exactly where they begin and end, even though the quotes aren’t actually a part of the string. In this example, the variable FirstName is assigned the string “Bill”, and LastName is assigned “Gates”. WholeName is assigned to be equal to both FirstName and LastName. Notice the & separating the FirstName and LastName variables on the right side. In VB.NET, & sticks two strings together, or concatenates them.
What’s wrong with this page?
There’s no space between the first and last names. You have to add the space when you stick them together. Change the line that assigns a value to WholeName in the preceding page to look like this:
WholeName = FirstName & " " & LastName
This time, three strings are concatenated: the one in FirstName, a space, and then the one in LastName. You can see the result:
Creating variables with a value
Here’s a shortcut for you. Instead of declaring all your variables and then assigning values to them as a separate step, you can do it all at once!
Imports System Module HelloWorld Public Sub Main() Dim FirstName As String = "Bill Dim LastName As String = "Gates" Dim WholeName As String = FirstName & " " & LastName Console.WriteLine(WholeName) End Sub End Module
This handy technique can save you a few keystrokes.
Making your code readable with comments
Comments, also called remarks, are the way you include notes to yourself or others inside your program without changing the way it works.
In Visual Basic, you can use the single-quote (or apostrophe) to indicate that the rest of the line is a comment.
Imports System Module HelloWorld Public Sub Main() ' This program calculates ' the total cost by adding ' the price and tax. Dim Cost, Tax, Total As Integer Cost = 40 Tax = 2 Total = Cost + Tax Console.WriteLine(Total) End Sub End Module
Note that you need a new apostrophe at the beginning of each new comment line.
You also can put a comment on the same line as code. Again, the comment starts with the apostrophe and ends at the end of the line:
Total = Cost + Tax ' This line does the sum
When you are testing your program, you can temporarily disable some lines you’ve written, but still easily get them back later if you need to. Rather than delete a line of code, simply put an apostrophe in front it. The apostrophe turns the line into a comment. The line of code no longer affects the way the page works, but it’s there if you want to bring it back. To put that line of code back into service, simply remove the apostrophe. Adding an apostrophe is called commenting-out a line of code. Removing the apostrophe is referred to as un-commenting the code.
In this article, you discovered variables—how to create them, assign values to them, do math with them, and display them. You also found out how to add comments to include notes to yourself or to others who might work with your code in the future. In the next article, you’ll discover functions and arguments.
About the Author
Bill Hatfield (MCSD, MCAD, MCP) is an internationally best-selling author of books on Internet, intranet and client/server technologies. Among his most recent books is ASP.NET For Dummies.
# # #