Home > Articles > Programming > Windows Programming

Writing Code with Visual Basic .NET

This article takes a comprehensive look inside the world of Visual Basic.NET, the simple, concise programming language designed for today’s Web environment. Begin by looking at such foundational concepts as variable and assignment, simple calculations and various functions; and end by examining a sample application.
This chapter is from the book

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 types—each 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 number—for example, if you're keeping track of the months of the year. Other times, you need to work with big numbers with many decimal places—for 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 10–45 for negative numbers; 1.401298 x 10–45 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 10–324 for negative numbers; 4.94065645841247 x 10–324 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 symbols—surely, 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 11—so 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 variable—one 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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020