485
Language Fundamentals Introduction to Microsoft Visual Basic 2010 Express Introduction to Projects | Operators and Operands Introduction to Variables | Using Variables Enumerations | Strings Incrementing/Decrementing Values Procedures and Functions Fundamentals Built-In Functions Introduction to Procedures Arguments and Parameters Introduction to Built-In Functions Static Variables Optional Arguments Overloading a Procedure Conversions Int/Fix Format Number Format Currency Format Percent Len Random Functions Conditional Statements Boolean Values | Logical Operations Introduction to Conditional Statements Functional Conditions Conditional Selections Managing Conditional Statements Classes Fundamentals Topics on Classes Introduction to Classes The Methods of a Class Class Construction and Destruction Structures The Shared Members of a Class Characteristics of Members of a Class Nesting a Class The Properties of a Class Operator Overloading Inheritance and Abstraction Built-In Classes Inheritance Polymorphism Class Abstraction Object Random Created by www.ebooktutorials.blogspot.in Content downloaded from www.functionx.com

Microsoft Visual Basic 2010 Tutorial

Embed Size (px)

DESCRIPTION

Content Downloaded from www.functionx.comFor more ebooks visit www.ebooktutorials.blogspot.in

Citation preview

Page 1: Microsoft Visual Basic 2010 Tutorial

Language Fundamentals

Introduction to Microsoft Visual Basic 2010 Express

Introduction to Projects | Operators and Operands

Introduction to Variables | Using Variables

Enumerations | Strings

Incrementing/Decrementing Values

Procedures and Functions

Fundamentals Built-In Functions

Introduction to Procedures

Arguments and Parameters

Introduction to Built-In Functions

Static Variables

Optional Arguments

Overloading a Procedure

Conversions

Int/Fix

Format Number

Format Currency

Format Percent

Len

Random Functions

Conditional Statements

Boolean Values | Logical Operations

Introduction to Conditional Statements

Functional Conditions

Conditional Selections

Managing Conditional Statements

Classes

Fundamentals Topics on Classes

Introduction to Classes

The Methods of a Class

Class Construction and Destruction

Structures

The Shared Members of a Class

Characteristics of Members of a Class

Nesting a Class

The Properties of a Class

Operator Overloading

Inheritance and Abstraction Built-In Classes

Inheritance

Polymorphism

Class Abstraction

Object

Random

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 2: Microsoft Visual Basic 2010 Tutorial

Language Topics

Strings

Date and Time Values

Message Boxes

Input Boxes

Delegates

Namespaces

Data Reading and Formatting

Custom Libraries

Error Handling

Events

Exception Handling

Introduction to Errors and Debugging

Options on Debugging

Error Handling

Introduction to Exceptions

.NET Framework Support

File Processing

Introduction

File Streams

Exception Handling

Directories

Files

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 3: Microsoft Visual Basic 2010 Tutorial

Introduction to Microsoft Visual Studio

MSVB

Introduction

Microsoft Visual Basic is a computer programming environement used to create graphicalapplications for the Microsoft Windows family of operating systems. It uses a computerlanguage of the same name. Like every computer language, Visual Basic is used to giveinstructions to a computer. The instructions can be written from a text editor such as Notepad.Another way is to use a programming environment that is equipped with many tools thatmake it easy to work on projects, to create the necessary files, and to distribute a completedapplication.

To follow our lessons, you can use Microsoft Visual Studio 2010 or Microsoft Visual Basic 2010Express. To get Microsoft Visual Basic 2010 Express, get to the Microsoft web site and clickthe Visual Studio Express link.

Starting Microsoft Visual Basic Express

TTo launch Microsoft Visual Basic 2010 Express, you can click Start -> (All) Programs ->Microsoft Visual Studio 2010 Express -> Microsoft Visual Basic 2010 Express:

To launch Microsoft Visual Studio 2010, you can click Start -> (All) Programs -> Microsoft VisualStudio 2010.

The Microsoft Visual Studio Interface

The Main Menu

The top section of Microsoft Visual Studio displays the main menu divided in categories such asFile or Edit. The main menu is used like the menu of a normal application.

The Toolbars

Under the main menu, there is a toolbar. Normally, when the studio is launched, it displays theStandard toolbar as its default. Some additional toolbars will display in response to an action

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 4: Microsoft Visual Basic 2010 Tutorial

from you. Still, you can display other toolbars if you want. To do this:

On the main menu, click View -> Toolbars and click the toolbar of your choice

Right-click the main menu or any toolbar. In the that appears, click the desired toolbar

Toolbars are used in the same they are in other applications.

Microsoft Visual Studio's menus and toolbars can be customized. You can customize a menucategory on the main menu by adding a menu item to it. You can customize a toolbar by addinga button to it. To start, right-click anything on the main menu or on any toolbar and clickCustomize... For example, imagine you want to add an item named Start Without Debugging tothe left side of the Start button:

To do this:

a. Right-click the main menu or a toolbar and click Customize

b. On the Customize dialog box, click the Commands tab

c. Click the Toolbars radio button

d. In the Toolbars combo box, select the toolbar that will host the button. For our example,that would be Standard

e. In the Controls list, click the button that will come after the new button. For our example,that would be Start / Continue:

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 5: Microsoft Visual Basic 2010 Tutorial

f. Click Add Command...

g. In the Categories list of the Add Command dialog box, select the category that has thebutton you want. For our example, that would be Debug

h. In the Commands list, click the desired button or menu item. For our example, that wouldbe Start Without Debugging

i. After makiing the selection, click OK

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 6: Microsoft Visual Basic 2010 Tutorial

j. On the Customize dialog box, click Close:

In the same way, you can customize any toolbar and any menu category.

The Start Page

The Start Page is the main body of Microsoft Visual Studio or Microsoft Visual Basic Expresswhen it has been launched. It starts on top with a tab labeled Start Page. The main body ofMicrosoft Visual Basic Express displays Microsoft Visual Basic 2010 Express. The left sectionshows two labels: New Project... and Open Project... When some projects have been previouslycreated or used, their names appear under Open Project... When you work on a project, theStart Page is usually in the background but it is represented by a tab. At any time, to displaythe Start Page:

You can click the Start Page label in the top section of the Code Editor

On the main menu, you can click View -> Start Page

Showing and Closing a Window

When you start or open a project, the studio makes some windows available. These are themost regularly used windows. If you think that one of them is not regularly used in your typesof assignments, you can remove it from the screen. To hide a window, you can click its Closebutton .

All of the windows you can use are listed in the View menu. Therefore, if a window is notdisplaying, you can click View on the main menu and click a window of your choice.

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 7: Microsoft Visual Basic 2010 Tutorial

Auto Hiding a Window

When working on a project, you will use a set of windows that each accomplishes a specificpurpose. Some windows are represented by an icon but hide the rest of the body. To displaysuch a window, you can position the mouse on it. This would expand the window:

If you expand a window, it would display a title bar with three buttons. One of the button iscalled Auto Hide:

If you expand a window but find out you don't need it any more, you can just move the mouseaway. The window would return to its previous state. Based on this functionality, if you areworking with a window and move the mouse away, it would retract. If you need it again, youwould have to reopen it using the same technique. If you are going to work with a certainwindow for a while, you can keep it open even if you move the mouse away. To do this, youcan click the Auto Hide button. If clicked, the Auto Hide button changes from pointing left topointing down:

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 8: Microsoft Visual Basic 2010 Tutorial

By default, the studio installs some windows to the left and some others to the right of thescreen. You can change this arrangement if you want. To do this, expand a window, then clickits title bar and start dragging. While you are dragging, to assist you with a new position, thestudio displays five boxes:

Docking a Window to a Side of the Studio

To position a window on one side of the studio, drag its title bar to the box that represents thatside. When you get to a side, a transparent blue rectangle would be drawn to indicate thepossible position. Drop the window to either the most left guiding box to position it to the leftof the screen, or to the most right guiding box to position it to the right of the screen. Here isan example:

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 9: Microsoft Visual Basic 2010 Tutorial

or

To position a window to the top or the bottom side of the studio, drag its title bar to either themost top guiding box to position it to the top of the studio or to the most bottom guiding boxto position it to the bottom of the studio. Here is an example:

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 10: Microsoft Visual Basic 2010 Tutorial

Docking a Window Above or Below Another

To make two windows share an area, you can position one above or below an existing window.Of course, you must first have a window as reference. Then, drag the second window to theexisting window. Drop it in the

This

Becomes

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 11: Microsoft Visual Basic 2010 Tutorial

Floating Windows

Most of the windows you will use are positioned on one side of the screen. If you want, you canhave a window that stays on top of other windows but is not "glued" to one side. Such a windowis said to float. To float a window, drag its title bar and release it somewhere in the middle of thescreen but not on a guiding box.

When a window is floating, it displays a Maximize button on the title bar. If you click thisbutton, the window occupies the whole interface of Microsoft Visual Studio. In the same way, ifyou double-click the title bar, the window gets maximized.

If a window is currently floating and you want to dock it, right-click its title bar and click Dock:

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 12: Microsoft Visual Basic 2010 Tutorial

If a window is currently docked and you want to float it, right-click its title bar and click Float.

Coupling Windows

You can make two or more windows share one side of the screen or to share an area. To do this,first expand and dock the window that you will use as the base (or reference). Then, drag the titlebar of the window that will share the area to its target until the bottom part of the base windowshows a highlighted and a non highlighted area:

Then release the mouse:

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 13: Microsoft Visual Basic 2010 Tutorial

To remove a window that shares an area, drag its tab away:

To position a window to the left or the right of an existing window, first drag the second windowto where the existing window is. Then click the left (or the right, depending on the side you want)guiding box of the multiple-box.

This

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 14: Microsoft Visual Basic 2010 Tutorial

becomes this

In the same way, you can make two or more windows share the same area.

Tabbed Windows

You can make a window display its tab in the top section of the Code Editor and share the areawith it. There are two ways yon do it

You can drag a window and drop it on the tab of the Start Page.

This

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 15: Microsoft Visual Basic 2010 Tutorial

becomes this

If a window is already represented with a tab on top of the Code Editor, you can drag the secondwindow and drop it to the left or of the right tab of the existing window.

You can right-click Dock as Tabbed Document

Home Copyright © 2010 FunctionX, Inc. Next

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 16: Microsoft Visual Basic 2010 Tutorial

Introduction to Projects

The Visual Basic Language in Microsoft Visual Basic

The Basic

Microsoft Visual Basic is not just a production environment. It also includes a fully functionallanguage that can stand on its own. The language started as Basic, then QuickBasic or QBasic.It first went through various changes. In 2002, Microsoft created a new serious language thatcan understand and use the .NET Framework. Microsoft Visual Basic is used to create graphicalapplications, also referred to as Graphical User Interface (GUI) applications, web-basedapplications, and other types of applications. In order to effectively create these applications,you must be familiar with the language used in this programming environment.

In our lessons, we are going to study the language that serves as a foundation to theMicrosoft Visual Basic programming environment.

Introduction to Projects

The primary job of an application is to show its results on the monitor. A console application isone that displays its results in a black window referred to as a DOS window. In some of ourlessons, we will create those types of applications. The Visual Basic language provides arectangular object called a message box. If you create a Visual Basic application, you candisplay the results in a message box. That's what we will use in most of our lessons.

To create an application, you start with a project. There are two main ways you can create a VisualBasic project. You can use a text editor or a programming environment.

A Program's File

To create a program, you write the necessary instructions in a text-based document. This is called asource file. A source file that contains Visual Basic instructions is a regular, simple, ASCII, text-basedfile. It has the extension .vb as a Windows file.

Practical Learning: Starting a Project

1. Start Notepad

2. To save the empty document, on the main menu of Notepad, click File -> Save

3. In the top combo box, locate and select the C: drive

4. Click the New Folder button

5. Set the name to Exercise1 and press Enter

6. Display that folder in the top combo box

7. Specify the name of the file as Exercise.vb

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 17: Microsoft Visual Basic 2010 Tutorial

8. Click Save

Introduction to Modules

In Visual Basic source file, you write code as we will learn throughout our lessons. The code that isconform to the Visual Basic language is included in a section known as the module. This section startswith the Module keyword followed by a name and ends with the End Module expression. Everythingbetween the line that has Module and the line that has End Module belongs to the same entity.Based on this, a simple file in Visual Basic would have the following:

Module ModuleName

End Module

Practical Learning: Introducing Modules

1. In the empty document, type the following:

Module Exercise

End Module

2. On the main menu, click File -> Save

Introduction to Procedures

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 18: Microsoft Visual Basic 2010 Tutorial

A procedure is a section of code that takes care of a specific task. In a module, the basic formula of aprocedure is:

Sub ProcedureName()

End Sub

Notice that it ends with the End Sub line. Because a module holds the code of a Visual Basicprogram, a procedure is included inside the start and the end of the module section. This would bedone as follows:

Module ModuleName Sub ProcedureName()

End Sub

End Module

We will come back to procedures in another lesson. For now, the most fundamental procedure used inVisual Basic is called Main. In a program, the Main procedure is the entry point. That is where theprogram starts.

Another common procedure highly used in Visual Basic is called MsgBox. As its name indicates, theMsgBox procedure is used to display a message in a dialog box. To make this happen, you caninclude the message inside the parentheses of MsgBox. The message itself should be included indouble-quotes. An example would be:

MsgBox("Whatever")

To distinguish a procedure from other items used in a program, we will sometimes write it followed byparentheses. Examples are Main() and MsgBox().

The MsgBox() procedure provides more details. We will come back to it in Lesson 7.

Practical Learning: Introducing Procedures

1. Change the document as follows:

Module Exercise Sub Main() MsgBox("Welcome to the Wonderful World of Visual Basic.") End SubEnd Module

2. On the main menu, click File -> Save

Building a Program

As mentioned already, you write the instructions of your project in English. But the computer doesn'tunderstant it. The instructions must be translated in a language the computer can understand. Thatlanguage is called machine language. To translate the instructions from English to machine dialect,you use a program named a compiler. In reality, a compiler is a group of sub-programs thataccomplish various goals to get a functional program at the end. The end result is a program that canbe executed in a computer other than the one you used to create the project. That final program iscalled an executable.

Ae mentioned already, a compiler is a computer program made of internal other sub-programs. Oneof the sub-programs, in fact probably the first, of a compiler is called a parser. A parser "scans" a filethat contains (part of) the program. It checks the syntax, keywords, unknown words, and some otherroutines. If the parser finds a problem, which could be anything, either it stops or it continues makinga list of the mistakes it found. Then it displays this list to you to fix. Sometimes it would point to theexact line where the/a problem was found. Sometimes it would point to the line where the problemshowed its impact although the problem may be found somewhere else. With experience, you willknow how to fix the programs or troubleshoot the problems.

If the parser doesn't find any problem, or after you have fixed the problems, it (the parser) passes itsresult(s) to the compiler. The compiler calls another program called a linker. If the program containsjust one file, the linker considers it. If the program contains more than one file, the linker considersthem. The linker gathers some of the files that the compiler shipped with (those files that yourprogram needs in order to work), puts them together ("links" them) with your file(s) to get yourinstructions in a manner that can produce a suitable result. If there is no significant problem, thecompiler creates the executable. This doesn't mean that everything is alright, it only means that the

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 19: Microsoft Visual Basic 2010 Tutorial

compiler thinks that everything is alright: it is still possible that the result may not be what you wouldexpect. We will come back to these issues.

To make your life easier, all of the sub-programs (parser, linker, debugger, etc) that ship with VisualBasic are grouped in one large program: the compiler. Therefore, from now on, we will use the word"compiler" to refer to the program you use to translate your English instructions into a machinelanguage.

Microsoft created and makes freely available a Visual Basic compiler you can use to create yourapplications. The Visual Basic compiler is named vbc. A compiler is primarily a computer program,that is an executable. As such, it uses to extension .exe. Therefore, the compiler we will use to createour program is called vbc.exe.

As mentioned already, the vbc.exe compiler is freely available. You can get it by downloading the.NET Framework from the Microsoft web site. Normally, you are likely to have the .NET Frameworkinstalled in your computer already. By default, it is installed inC:\Windows\Microsoft.NET\Framework\v4.0.21006.

You can use the vbc.exe to create programs from the Command Prompt. To do this, you can add thecompiler's path to the Path of the Environment Variables. To start, use a file utility such as WindowsExplorer and display the folder where vbc.exe is installed. Here is its path in Windows Explorer:

Select the path in the top combo box and copy it to the clipboard. Start the Control Panel. ClickSystem and Security:

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 20: Microsoft Visual Basic 2010 Tutorial

In the System and Security section, click System:

In the System window, click Change Settings. In the System Properties dialog box, click the Advancedtab. Click the Environment Variables button:

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 21: Microsoft Visual Basic 2010 Tutorial

In the System Variables section, double-click Path or click it and click Edit:

Press the End key, type a semi-colon ";". Paste the value you had copied from the clipboard:

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 22: Microsoft Visual Basic 2010 Tutorial

Click OK three times.

Open the Command Prompt. Type CD\ and press Enter to move to the root drive. Type CD and aspace, followed by the folder (and sub-folder(s)) where the file is located, and press Enter. Tocompile, type vbc followed by the name of the file and its extension:

The file produced from this operation has the extension .exe. By default, it holds same name as thefile you had used. If you want to get an executable using a name of your choice, after vbc, type/out: followed by the name you want, followed by a .exe extension, followed by a space, and followedby the name of the file you had created, with its extension. The formula to follow would be:

vbc /out:NameOfExecutate.exe Filename.vb

The NameOfExecutate represents the name you want the executable to have. If the name you want isin one word, you can just type it. Here is an example:

vbc /out:Welcome.exe Exercise.vb

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 23: Microsoft Visual Basic 2010 Tutorial

If you want a name made of various words, you can include those words in double-quotes.

If you are creating your application using a text editor and if you create many files, when compilingthe project, you must remember to reference each file. To do that, in the last section, add the nameof each file with its extension:

vbc FileName1.vb FileName2.vb FileName_n.vb

The executable you get is the one you can use on other computers and that you can distribute toother people.

Executing a Program

After building the code, you and your users can execute it. If you are working from the CommandPrompt, to execute the project, type the name of the file that has the .exe extension and press Enter:

If you are working from Microsoft Visual C# 2010 Express or from Microsoft Visual Studio, to executean application, on the main menu, you can click Debug -> Start Debugging.

A Solution and its Projects

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 24: Microsoft Visual Basic 2010 Tutorial

Creating a Project

Although you can creat a complete and fully functional application using a text editor, MicrosoftVisual Studio and Microsoft Visual Basic 2010 Express provide a graphical environment that is moreconvenient. You start by creating a project. To create a project:

On the main menu, click File -> New Project...

On the Start Page, click New Project...

Press Ctrl + N

Creating a Solution

When you start a new application from the New Project dialog box, you are asked whether youwant to create a new solution too, and you must give it a name. By default, the new project andsolution would hold the same name. If you accept the suggestions, you would get a main folderwith the name of the project. Inside of that folder, there would be a folder with the same name.That inside folder would represent the project.

After creating a solution, its name appears on the title bar of Microsoft Visual Studio. The name ofthe project would appear in the Solution Explorer.

Practical Learning: Introducing the Visual Basic Language

1. Launch either Microsoft Visual Studio or Microsoft Visual Basic 2010 Express

2. On the main menu, click File -> New Project...

3. If you are using Microsoft Visual Studio, in the left list, expand Visual Basic and click Windows.In the right list, click Empty Project. Change the Name to GeneralCensus before clicking OK

If you are using Microsoft Visual Basic 2010 Express, in the middle list, click ConsoleApplication. Change the Name to GeneralCensus

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 25: Microsoft Visual Basic 2010 Tutorial

Click OK

Introduction to Managing Solutions and Projects

The Solution Explorer

The Solution Explorer is a window that displays a list of the files that make up a project. To accessthe Solution Explorer:

If the Solution Explorer is not yet showing on the screen:

On the main menu, click View -> Solution Explorer

On the Standard toolbar, click the Solution Explorer button

If the Solution Explorer is already showing, click its tab

The Solution Explorer is made of four sections. Like every regular window, the Solution Explorer isequipped with a title bar that displays its name on the left side and three buttons on the rightside:

The Window Position button displays a menu when you click it:

The Float option is enabled if the window is docked to a side of the screen. The Float option isdisabled if the window is already floating. If the window is docked and you click Float, it wouldbe moved from its docked position and would float. As an alternative to float a docked window,drag its title bar away from its docked position:

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 26: Microsoft Visual Basic 2010 Tutorial

To dock a floating window, drag its title bar

Under its title bar, the second section of the Solution Explorer is a toolbar::

The Properties button allows you to display the Properties window

The Show All Files button is used to show the hidden files of the project

As its name indicates, the Refresh button is used to refresh the list of files and resources ofthe project

The View Code button is used to show the code of a class

The third part of the Solution Explorer is its body. It shows the folders, files, and resources thatare part of the current project. To expand a node, you can either click its button or double-click itsname. To collapse a node, either click its button or double-click it.

The root of the list is the name of the solution. Under the root is the name of the current project.If the solution contains more than one project, the name of each project is represented under thesolution. Inside of the project are its folders, files, and resources. The first item under a projectname is References. After the References node, there are the names of the classes that are part ofthe project.

The fourth part of the Solution Explorer is its tab.

The Properties Window

The Properties window shows the Windows operating system's details of the files or resources usedin a project. To display it:

If the Properties window is not yet displaying

Oon the main menu, click View -> Properties window

On the Standard toolbar, click the Properties button

If the Properties window is displaying already, click its tab

The display and rectangular behavior of the Properties window follows the description we had forthe Solution Explorer.

To show the operating system's characteristics of a project or a file, in the Solution Explorer, clickthe object:

If you click a solution, the Properties window would show its name and its location

If you click a project, the Properties window would show its project file

If you click a file, the Properties window would show its name (in the File Name field) and itslocation (in the Full Path) field

The Properties window displays different fields depending on the item selected in the SolutionExplorer. You can change some things in the Properties window. When a field is disabled, it meansyou cannot modify it.

Managing a Solution

Introduction

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 27: Microsoft Visual Basic 2010 Tutorial

A solution is used to coordinate the different aspects of an application that is being created. When you have created aproject, the name of the solution displays as the top node of the tree in the Solution Explorer:

The title bar of the studio displays the name of the solution in the left section:

If you start saving a project for the first time, it would bring the Save Project dialog box. By default, Microsoft VisualStudio selects your personal directory as the path to the solution. This is called the location. In the location, MicrosoftVisual Studio creates a folder as the solution of the project. The solution must have, or must be stored, in its own folder.As mentioned earlier, Microsoft Visual Studio uses the name of the project as the name of the solution. To rename thesolution, you can change the string in the Solution Name text box. Remember that you can enter the name of the projectin the Name text box. Here is an example:

When you save a project (for the first time), by default, Microsoft Visual Studio creates a new folder for it in theDocuments\Visual Studio 2010\Projects folder. It uses the name of the solution to name the folder. It creates some filesand stores them in that new folder. Then, it creates a sub-folder, using the name of the project, inside of the folder of thesolution. Besides the sub-folder with the name as the project, it creates another folder named debug. It also createsanother folder named Debug in the sub-folder of the name of the project. In each folder and some other folders, itcreates some files that we will not pay attention to for now.

If the project had already been saved but you want to change the name of the solution, on the main menu, you can clickFile -> Save solution-name.sln As... This would bring the Save File As dialog box where you can specify the name of thesolution and click Save.

Renaming a Solution

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 28: Microsoft Visual Basic 2010 Tutorial

If you don't like the name of a solution, to rename it, in the Solution Explorer, right-click it and click Rename:

As an alternative, in the Solution Explorer, click the name of the project, in the Properties window, click the value of the(Name) field, then edit it or type a new one:

Deleting a Solution

Deleting a Solution is equivalent to deleting a file. To delete a solution, use a file utility such as Windows Explorer, locatethe folder that contains the solution, and delete it.

Managing a Project

Saving a Project

If you are creating your application using a text editor, you must save your file(s) in a folder you will create. WhenMicrosoft Visual Studio 2010 (any edition) is installed, it creates a folder named Visual Studio 2010 in your Documentsfolder. The Documents folder is called your personal drive or your personal directory. Inside of the Visual Studio 2010folder, it creates a sub-folder named Projects. By default, this is where it would save your projects, each with its ownfolder.

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 29: Microsoft Visual Basic 2010 Tutorial

To save a project, on the Standard toolbar, you can click the Save All button . Alternatively, on the main menu, youcan click File -> Save All. If the project had already been saved but you want to save it under a different name, on themain menu, you can click File -> Save project name As...

Opening a Project

There are a various ways you can open an existing project:

On the main menu, click File -> Open Project...

On the Start Page, click Open Project...

Press Ctrl + Shift + O

Adding a Project

A solution in Microsoft Visual Studio can contain one or more projects. That is, after creating the first project, you can addanother project to the same solution and you can add as many projects as you want.

To add a new project to a solution (in Microsoft Visual Studio):

On the main menu, click File -> Add -> New Project...

In the Solution Explorer, right-click the name of the solution, position the mouse on Add, and click New Project...

This would display the Add New Project dialog box. In the Templates list, select the type of project you want. Accept orchange the name of the project, then click OK.

The names of the different projects are listed in the Solution Explorer.

Renaming a Project

To rename a project, in the Solution Explorer, right-click its name under the solution and click Rename. Type the newname and press Enter.

Managing the Files of a Project

Adding a File to a Project

As mentioned already, a project can contain many files. If you are using a text editor, you can create and save filescontinuously as you see fit. If you are using Microsoft Visual C# 2010 Express or Microsoft Visual Studio, to add a new fileto a project:

On the main menu, click Project -> Add New Item...

In the Solution Explorer, right-click the name of the project, position the mouse on Add, and click New Item...

This would display the Add New Item dialog box. From there, select the type of file you want. Accept or change its name.Then click Add.

When a project is made of various files, each file is represented by a label in the top section of the Code Editor. Here areexamples:

Each file is also represented in the main menu under Windows.

Adding an External File

When working on a project, if there is a file in another project and you want to use that file in your project, you can

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 30: Microsoft Visual Basic 2010 Tutorial

import that file. To do this;

On the main menu, click Project -> Add Existing Item...

In the Solution Explorer, right-click the name of the project to which you want to import the file, position the mouseon Add, and click Existing Item...

Any of these actions would display the Add Existing Item dialog box with the name of the project on the title bar. Locatethe file, select it, and click Open.

Accessing a File

If you are using a text editor to write your code, you can use that editor to open a file. For example, in Notepad, you canclick File -> Open... If you are trying to open a source file, first change the file type combo box to All Files (*). Thenlocate the file from its folder and click Open.

In Microsoft Visual Studio or Microsoft Visual C# Express, if a file is a member of the current project, to open it:

On the main menu, click Window and click the name of the file

On the main menu, click File -> Open File...

In the top section of the Code Editor, click the label that holds the name of the file

Opening a File

To open a file:

In the Solution Explorer, double-click the name of the file

On the Standard toolbar, click the Open File button

This would display the Open File dialog box. From there, locate the file from its folder and click it.

Renaming a File

You can change the name of a file after starting a project. To do this, in the Solution Explorer, under the project thatholds the file, right-click the file and click Rename. Type the desired name and press Enter.

Removing a File From a Project

If you have a file in a project but do not need that file anymore, you can delete it. To remove a file, in the SolutionExplorer, under the project, right-click the name of the file and click Delete.

Practical Learning: Managing Files in a Project

1. If you are using Microsoft Visual Basic 2010 Express, in the Solution Explorer, right-click Module1.vb and click Delete.When asked whether you want to permanently delete, click OK.In either studio, to add a new file, on the main menu, click Project -> Add New Item...

2. In the middle list, click Code File

3. Set the Name to Management

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 31: Microsoft Visual Basic 2010 Tutorial

4. Click Add

Writing Code

After creating or opening a file, you can add the necessary code to it. Microsoft Visual Basic ships with many skeletoncodes you can use and customize. It writes the primary code for you and add all the necessary default behaviors. Once ithas done this, you can change or remove any section. To access these code skeletons, in the section of the file where youwant to add it, right-click and click Insert Snippet...:

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 32: Microsoft Visual Basic 2010 Tutorial

In the menu that comes up, double-click a category:

Then double-click another category. This would display a list of code types:

If you see the type of code you want to use, double-click it.

In some cases, if you have already written some code, you may want to change it or rather add some code to it. TheCode Editor provides some skeleton codes you can use. To use this approach, right-click the code you want to modify andclick Surround With... In the list that appears, double-click the desired option.

Practical Learning: Writing Code

In the empty document, type the following:

Module Statistics

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 33: Microsoft Visual Basic 2010 Tutorial

Sub Main() MsgBox("We are performing a general census of our population") End Sub

End Module

The Starting File of a Project

If you add many files to a project, you must specify what file should be processed first. If you create a console applicationusing Microsoft Visual Studio or Microsoft Visual Basic 2010 Express, the first file you create is set as the default.

To specify the starting file of your project, on the main menu, click Project -> ProjectName Properties... In the StartupObject combo box, select the file.

Practical Learning: Specifying the Starting File of a Project

1. On the main menu, click Project -> GeneralCensus Properties

2. Click the arrow of the Startup Object combo box and select Statistics

3. To test the application, on the main menu, click Debug -> Start Debugging

4. Read the text of the message box

5. Click OK on the message box

Code Colors

Code is written in a wide area with a white background. This is the area you use the keyboard to insert code with commonreadable characters. The Code Editor uses some colors to differentiate categories of words or lines of text.

The colors used are highly customizable. To change the colors, on the main menu, you can click Tools -> Options... In theOptions dialog box, in the Environment section, click Fonts and Colors. To set the color of a category, in the Display Itemssection, click the category. In the Item Foreground combo box, select the desired color. If you want the words of thecategory to have a colored background, click the arrow of the Item Background combo box and select one:

In both cases, the combo boxes display a fixed list of colors. If you want more colors, you can click a Custom button todisplay the Color dialog box that allows you to "create" a color.

Indentation

Indentation is another feature that makes your program easy to read. Indentation is a technique of grouping lines of codeby category. To delimit the items of your code, you should indent them by two empty spaces or one tab. Indentationshould be incremental. That is, when a line of code appears to be a child of the previous line, the new line should beindented.

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 34: Microsoft Visual Basic 2010 Tutorial

To control the indentation of your code, on the main menu, click Tools -> Options... In the left list, Text Editor amdexpand Basic. You can then use the options in VB Specify and Editor:

After making the changes, click OK to validate or Cancel to ignore.

Accessories for Code Writing

Comments

A comment is text that the compiler does not process when reading your code. As such, a comment can be written anyway you want. In the Visual Basic language, the line that contains a comment can start with a single quote. Here is anexample:

Module Module1

Sub Main() ' This line will not be considered as part of the code End Sub

End Module

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 35: Microsoft Visual Basic 2010 Tutorial

Alternatively, you can start a comment with the Rem keyword. Anything on the right side of rem, Rem, or REM wouldnot be processed. Here is an example:

Module Module1

Sub Main() ' This line will not be considered as part of the code Rem I can write anything I want on this line End Sub

End Module

Comments are very useful and you are strongly suggested to use comments regularly. They can never hurt your code andthey do not increase the size of your application. Comments can help you and other people who read your code to figureout what a particular section of code is used for, which can be helpful when you re-visit your code after months or yearsof not seeing it.

White Spaces

When writing code, you will have to separate different parts with spaces, like the one between Sub and Main. This isreferred to as white space. The amount of space you put between two words is not important. The compiler would ignorethe white spaces between words. This means that Sub Main() and Sub Main() would the same effect. In the sameway

Sub Main()

and

Sub Main()

would produce the same effect.

Previous Copyright © 2008-2010 FunctionX Next

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 36: Microsoft Visual Basic 2010 Tutorial

Operators and Operands

The Values of an Application

Introduction

When interacting with the computer, at times, a user might be asked to provide a value. Atother times, the user might be presented with a value to manipulate. During this interaction,the values, any of them, are stored and retrieved at will. To make this possible, the computeruses its memory.

The computer memory is an area used to receive information, store it, and then make thatinformation available when requested. The computer only makes its memory available to you.It doesn't know and cannot predict the type of value that your particular program would need.This is because one program might be made to manipulate numbers while another programmight be made for names. Because the information stored in the computer can be as variedas possible, it may be segmented (the word segment is taken in its English meaning and notin its Assembly definition) in portions or various pieces.

The pieces of information stored in the computer memory come, go, and change on a regularbasis. For this reason, a piece of information stored in the computer memory is called avariable. A variable is an area of the computer memory used to store a value. Because therecan be many kinds of values stored in the computer memory, a variable stores only one kindof value.

The Stack

To manage the various types of values that can be used in a program, the computer is equippedwith two types of memory. The Random Access Memory, also called RAM, is a type of memorythat is "filled" with values when the computer comes up and while a person is using thecomputer. When the computer gets shut down, the RAM looses everything that was put in thatmemory so that the next time the computer comes up, the RAM "forgets" the values that wereentered in it the previous time. In other words, when the computer boots up, the RAM is emptyand new values must be entered in it.

Another type of memory that the computer uses is called Read-Only Memory (ROM). In thisarea, the computer stores values that "stick" in it and stay there. Such values can be calledwhen needed and, unless they are explicitly deleted, when the computer gets shut down, thevalues go back to the ROM. The next time the computer comes up, the values of the ROM willbe available. The values of the ROM stay there and are retrieved only when requested.

The RAM can be illustrated like a group of small boxes. When the computer boots up, or whilethe computer is coming up, they are empty:

Each one of these small boxes is named a bit. It can have only one of two values. From ourillustrations, when the box is empty, the bit has a value of 0. When it is filled (it cannot be half-full or half-empty), it has a value of 1.

When the computer has finished booting up, some values are asked to occupy this area. In the

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 37: Microsoft Visual Basic 2010 Tutorial

same way, when you start a program like Notepad, it is "loaded" in this memory. This meansthat part of the RAM is filled with some values. Some other parts of the RAM are filled withgarbage or values that don't mean anything to you:

When your application comes up, you can ask the computer to put some values for yourapplication. Remember that you are not, or your application is not, the only one that needs touse an area of the computer memory. Because there can be so many values that differentapplications store, retrieve, and manipulate all day long or as long as the computer is on, theoperating system reserves an area of this memory for applications like yours. To make surethere is no mess, the computer is in charge of this area of memory. When you want to store avalue in that memory, you let the computer know. The computer then puts (the verb used is"push") that value in the necessary area of the memory (the computer, and not you, decideswhere to put the value). When the value is not used anymore, the computer removes (the verbused is "pop") that value. This allows the computer to make that area of memory available tothe applications that would need it. This area of memory that the computer reserves for thevarious applications, and is in charge of, is called the stack.

Variable Declaration

If you want to use an area of memory of the computer, in other words if you want to store avalue in that memory, you must ask the compiler to reserve a portion of memory for your value.Making this request is referred to as declaring a variable. To formulate this request, you mustfirst type the Dim keyword:

Dim

To make this request, you must provide a name for the variable. The name of a variable is alsocalled an identifier. When the computer reserves an area of memory, it uses a name to be ableto locate that area of memory. Later on, when you want to store a value in that memory, youwill communicate a name to the compiler. The compiler will know the area of memory you arereferring to by its name. This means that, at the right time, the name is used by both you andthe compiler to know what portion of memory you are referring to. The name itself is not storedin the memory per se. It only allows you and the compiler to access a particular area ofmemory.

The Name of a Variable

There are rules you should, and usually must, follow when naming your variables. The rules tofollow are:

The name of a variable can consist of only one a letter (a, b, c, d, e, f, g, h, i, f, k, l, m, n, o, p, q, r,s, t, u, v, w, x, y, z. A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, or Z)

The name of a variable can start with with a letter

The name of a variable can start with with an underscore _.If the first character is an underscore, it must be followed by a letter

After the first character that is a letter or an underscore, the name can contain letters, underscores,or digits (0, 1, 2, 3, 4, 5, 6, 7, 8, or 9)

The name cannot have an empty space

The name cannot have any special character (! @ # $ % ^ & * + - = ~ ` < > , . : ; " ' { [ } ] | \ )between letters or digits except the underscore as specified above. Some characters can be used asthe last character of a name. We will encounter them when necessary

Can have up to 255 characters but refrain from using a name that is too long (more than 64characters)

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 38: Microsoft Visual Basic 2010 Tutorial

Must be unique inside of the procedure or the module it is used in

A name cannot be one of the words reserved for the Visual Basic language's own use. Thesewords are also called keywords. Therefore, avoid using the following words to name a variable(this list includes official Visual Basic language keywords and words or expressions you shouldavoid):

AddHandler AddressOf Alias And AndAlso

Ansi As Assembly Auto Boolean

ByRef Byte ByVal Call Case

Catch CBool CByte CChar CDate

CDbl CDec Char CInt Class

CLng CObj Compare Const Continue

CSByte CShort CSng CStr CType

CUInt CULng CUShort Custom Date

Decimal Declare Default Delegate Dim

DirectCast Distinct Do Double Each

Else ElseIf

End EndIf Enum Equals Erase

Error Event Exit Explicit False

Finally For Friend From Function

Get GetType GetXmlNamespace GoSub GoTo

Group By Group Join Handles If Implements

Imports In Inherits Integer Interface

Into Is IsFalse IsNot IsTrue

Join Key Let Lib Like

Long Loop Me Mid Mod

Module MustInherit MustOverride MyBase MyClass

Namespace Narrowing New Next Not

Nothing NotInheritable NotOverridable Object Of

Off On Operator Option Optional

Or Order By OrElse Overloads Overridable

Overrides ParamArray Partial Preserve Private

Property Protected Public RaiseEvent ReadOnly

ReDim REM RemoveHandler Resume Return

SByte Select Set Shadows Shared

Short Single Skip Skip While Static

Step Stop Strict String Structure

Sub SyncLock Take Take While Text

Then Throw To True Try

TryCast TypeOf UInteger ULong Unicode

UShort Until Using Variant

Went When Where While Widening

With WithEvents WriteOnly Xor

Although you must always avoid using keywords as names of your variables in your program, ifyou insist on using one of these keywords to name something, put the word between squarebrackets. An example would be [True]

The Visual Basic language is not case sensitive. This means that NAME, name, and Namerepresent the same word. This means that, in the same section (normally called scope), youcannot have two variables with the same name that differ only by their cases. This would causea name conflict. If you declare a variable in a scope and use it later with a different case, as

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 39: Microsoft Visual Basic 2010 Tutorial

long as the same characters are used on both names, the Visual Basic compiler would knowwhat variable you are referring to and there would not be any conflict.

Option Explicit

You should always make sure that you declare a variable before using it. Otherwise you may usetwo variables that seem to be different but because of a mistype, you would think that you areusing two variables. Examples are Type and Tape.

To indicate to the compiler that each variable must be declared prior to being used, in the topsection of your source file, you should type:

Option Explicit On

Values Fundamentals

Introduction

Besides the name, the second piece of information the compiler needs is the amount, also calledsize, of memory that the variable would need. This is because different values use differentamounts of space. For example, the title of a book certainly needs more space than the numberof pages of a daily newspaper.

The amount of space that a variable can occupy is referred to as its data type. To limit theamount of gymnastics to perform, the compiler uses categories of data types. For example, itcan decide that a simple number would use one small "box" to store its value. On the otherhand, it may decide that it would need ten "buckets" to store the title of a movie.

When you create a program, you can let the compiler know the amount of memory you wouldneed for a particular variable. You can do this by specifying the most appropriate category. Aftertelling the compiler that this particular variable would be used to store a number, you canchange it in the middle of the program and decide to store an employee's maiden name. On theother hand, some numbers will require more space than others. For example, imagine you wantto store the population of countries in a variable. In this case you would request memory thatcan hold a large number. This type of variable must be able to hold the population of China aswell as the population of Burundi. Of course, this same space can hold the number of pages of adaily newspaper. This means that, sometimes, there will appear to be waste of memory.Nowadays, you should not be too concerned with memory as it is becoming less expensive: it isbetter to have a few empty "buckets" in the computer memory than to have unavailablememory.

To reduce the number of mistakes that could be due to a possible wrong value being stored in avariable, the Visual Basic compiler uses two mechanisms: variable initialization and conversion.

Practical Learning: Introducing Variables

1. Start Microsoft Visual Basic (either Microsoft Visual Studio or Microsoft Visual Basic 2010Express)

2. To create a new application, on the main menu, click File -> New Project

3. In the middle list, click Console Application

4. Set the Name to YNB1 (which stands for Yugo National Bank 1)

5. Click OK

6. In the Solution Explorer, right-click Module1.vb and click Rename

7. Type the new name as Training.vb and press Enter

8. On the main menu, click Project -> YNB1 Properties

9. Click the arrow of the Application Type box and select Windows Forms Application

10. Click the Close button to close the Property Pages window

A Review of Variable Declaration

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 40: Microsoft Visual Basic 2010 Tutorial

We saw that, to declare a variable, you use the Dim keyword, followed by a name. Here is anexample:

Module Exercise

Sub Main() Dim Something

End Sub

End Module

After declaring a variable like this, the compiler reserves a portion of the computer memory forthat variable but there may be two possible (small) problems: the compiler does not know howmuch space that variable would need to store its values and, because of this, the compiler wouldleave empty that area of memory.

To access the value of a variable, you can simply refer to its name. For example, you candisplay it to the user. We saw that you could use the MsgBox procedure to display a value. Hereis an example:

Module Exercise

Sub Main() Dim Something

Something = 25 MsgBox(Something) End Sub

End Module

Practical Learning: Declaring Variables

To declare some variables, change the file as follows:

Module Training

Sub Main() Dim CustomerName Dim AccountNumber Dim InitialDeposit End Sub

End Module

Value Conversion

We mentioned that you could declare a variable but not specify the type of value that would bestored in the memory area reserved for it. When you have declared a variable, the compilergives it an initial value. This is referred to as initializing the variable. Instead of the compilerdoing it, you too can initialize a variable. Initialization partially solves the two problems wementioned.

In reality, when you declare a variable, the compiler primarily considers it a string and reservesenough space to store any amount of characters. One way you can solve this confusion is toinitialize the variable.

To initialize a variable, type its name, followed by =, and followed by the desired value. Here isan example:

Module Exercise

Sub Main() Dim Something

Something = 25 End Sub

End Module

After initializing the variable, the new value is stored in its reserved area of memory. When youinitialize a variable, the compiler uses the given value to convert it to the appropriate type. Forexample, if you consider a variable with 25, it becomes considered an integral variable; that is, avariable whose memory can hold natural numbers.

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 41: Microsoft Visual Basic 2010 Tutorial

We mentioned that, after declaring a variable, you could change its value whenever you judge itnecessary. After declaring a variable as done in the above example, you can assign it any valueof you choice. Here are examples:

Module Exercise

Sub Main() Dim Something

Something = 25 MsgBox(Something)

Something = "Manchester United Football Club" MsgBox(Something)

Something = 237565.408 MsgBox(Something) End Sub

End Module

This is one of the unique features that make the Visual Basic (2005) language so flexible.

Requesting a Value

While many programs are meant to simply present values to the user, most applications areused to request values from the user. To make this possible and easy, Visual Basic provides aprocedure called InputBox. To use it, type it, followed by parentheses. In its parentheses, entera sentence that will serve as a guide to the user. The sentence itself should be included betweendouble-quotes.

A typical sentence would indicate what value (or what type of value) you want the user to enter.Here is an example:

InputBox("Enter your first name: ")

The input box appears as a message box with the addition of a text box that would receive theuser's value. Here is an example:

The user is expected to type a value in the text box. As mentioned for the variables, the valuethe user types is primarily considered a regular series of characters. To use that series, youmust convert it to the appropriate type. We will review the procedures used to convert thevalues.

The InputBox() procedure provides more details. We will come back to it in Lesson 7.

Visual Basic Operations

Introduction

An operation is an action performed on one or more values either to modify one value or toproduce a new value by combining existing values. Therefore, an operation is performed using atleast one symbol and one value. The symbol used in an operation is called an operator. Avariable or a value involved in an operation is called an operand.

A unary operator is an operator that performs its operation on only one operand.

An operator is referred to as binary if it operates on two operands.

The Line Continuation Operator: _

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 42: Microsoft Visual Basic 2010 Tutorial

If you plan to write a long piece of code, to make it easier to read, you may need to divide it invarious lines. You can do it as you would in any text editor. Here is an example:

Module Exercise

Sub Main() Dim Something

Something = "Manchester United Football Club" MsgBox(Something) End Sub

End Module

Notice that the variable Something and Manchester ... are written on different lines. As analternative, you can use the line continuation operator represented by a white space followed byan underscore and an empty space. Here is an example:

Module Exercise

Sub Main() Dim Something

Something = _ "Manchester United Football Club" MsgBox(Something) End Sub

End Module

The Parentheses: ()

Parentheses are used in two main circumstances: in a procedure as we have used Main,MsgBox and InputBox so far, or in an operation. The parentheses in an operation help tocreate sections in an operation. This regularly occurs when more than one operators are used inan operation. Consider the following operation:

8 + 3 * 5

The result of this operation depends on whether you want to add 8 to 3 then multiply the resultby 5 or you want to multiply 3 by 5 and then add the result to 8. Parentheses allow you tospecify which operation should be performed first in a multi-operator operation. In our example,if you want to add 8 to 3 first and use the result to multiply it by 5, you would write (8 + 3) *5. This would produce 55. On the other hand, if you want to multiply 3 by 5 first then add theresult to 8, you would write 8 + (3 * 5). This would produce 23.

As you can see, results are different when parentheses are used on an operation that involvesvarious operators. This concept is based on a theory called operator precedence. This theorymanages which operation would execute before which one; but parentheses allow you tocompletely control the sequence of these operations.

The Comma ,

The comma is used to separate variables used in a group. For example, a comma can be used todelimit the names of variables that are declared on the same line. Here is an example:

Module Exercise

Sub Main() Dim CustomerName, AccountNumber, InitialDeposit Dim RegularDeposit, TotalDeposits End Sub

End Module

The comma can also be used to separate the member of an enumeration or the arguments of amethod. We will review all of them when the time comes.

The Assignment Operator =

The assignment operation is used to make a copy of a value or the value of a variable and givethe copy to another variable. The assignment operation is performed with the = sign.

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 43: Microsoft Visual Basic 2010 Tutorial

After you have declared a variable, before using it, it must have a value. One way you can givea value to a variable is to assign one.

The Double Quotes: ""

A double-quote is used to delimit a group of characters and symbols. To specify this delimitation,the double-quote is always used in combination with another double-quote, as in "". What everis inside the double-quotes is the thing that need to be delimited. The value inside the double-quotes is called a string. Here is an example:

Sub Main() Dim Country

Country = "Grande Bretagne"End Sub

If a procedure expects a string, you can type that string in the parentheses of the procedure, wewill be using the MsgBox and InputBox procedures.

Practical Learning: Requesting Some Values

1. To use double-quotes and request some values, change the file as follows:

Module Training

Sub Main() Dim CustomerName Dim AccountNumber Dim InitialDeposit

CustomerName = InputBox("Enter Customer Name:") AccountNumber = InputBox("Enter Customer Acnt #:") InitialDeposit = InputBox("Enter Initial Deposit:")

MsgBox("Yugo National Bank") MsgBox(CustomerName) MsgBox(AccountNumber) MsgBox(InitialDeposit) End Sub

End Module

2. To test the program, on the main menu, click Debug -> Start Debugging

3. Enter the requested value as: Enter Customer Name: Gertrude Monay

Enter Customer Acnt #: 92-37293-30

Enter Initial Deposit: 450.00

4. When you have finished, return to your programming environment

The Colon Operator :

Most of the time, to make various statements easier to read, you write each on its own line. TheVisual Basic language allows you to write as many statements as necessary on the same line. Todo this, the statements can be separated by a colon. Here is an example:

Module Exercise

Sub Main() Dim CustomerName Dim AccountNumber Dim InitialDeposit

CustomerName = InputBox("Enter Customer Name:") AccountNumber = InputBox("Enter Customer Acnt #:") InitialDeposit = InputBox("Enter Initial Deposit:")

MsgBox("Yugo National Bank") : MsgBox(CustomerName) MsgBox(AccountNumber) : MsgBox(InitialDeposit) End Sub

End Module

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 44: Microsoft Visual Basic 2010 Tutorial

String Concatenation: &

The & operator is used to append two strings or expressions. This is considered as concatenatingthem. For example, it could allow you to concatenate a first name and a last name, producing afull name. The general syntax of the concatenation operator is:

Value1 & Value2

To display a concatenated expression, use the assignment operator on the field. To assign aconcatenated expression to a variable, use the assignment operator the same way:

Sub Main() Dim FirstName Dim LastName Dim FullName FirstName = "Francis " LastName = "Pottelson" FullName = FirstName & LastNameEnd Sub

To concatenate more than two expressions, you can use as many & operators between any twostrings or expressions as necessary. After concatenating the expressions or values, you canassign the result to another variable or expression using the assignment operator.

Practical Learning: Concatenating Some Strings

1. To use the string concatenator, change the file as follows:

Module Training

Sub Main() Dim CustomerName Dim AccountNumber Dim InitialDeposit

CustomerName = InputBox("Enter Customer Name:") AccountNumber = InputBox("Enter Customer Acnt #:") InitialDeposit = InputBox("Enter Initial Deposit:")

MsgBox("Yugo National Bank") MsgBox("Customer Name: " & CustomerName) MsgBox("Account Number: " & AccountNumber) MsgBox("Initial Deposit: $" & InitialDeposit) End Sub

End Module

2. To test the program, on the main menu, click Debug -> Start Debugging

3. Enter the requested value and, when you have finished, return to your programmingenvironment

Tabs and Carriage Return

Carriage Return-Line Feed

If you are displaying a string but judge it too long, you can segment it in appropriate sectionsas you see fit. To do this, you can use vbCrLf.

Practical Learning: Using Carriage Return-Line Feed

1. To use the Carriage Return-Line Feed, change the file as follows:

Module Training

Sub Main() Dim CustomerName Dim AccountNumber Dim InitialDeposit Dim Result

CustomerName = InputBox("Enter Customer Name:") AccountNumber = InputBox("Enter Customer Acnt #:") InitialDeposit = InputBox("Enter Initial Deposit:")

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 45: Microsoft Visual Basic 2010 Tutorial

Result = " =-= Yugo National Bank =-=" & vbCrLf & "Customer Name: " & CustomerName & vbCrLf & "Account Number: " & AccountNumber & vbCrLf & "Initial Deposit: $" & InitialDeposit MsgBox(Result) End Sub

End Module

2. To test the program, on the main menu, click Debug -> Start Debugging

3. Enter the requested values. Here are examples:

4. When you have finished, return to your programming environment

Carriage Return-Line Feed

From your experience with using the computer keyboard, you probably know already that, tocreate a tab white space, you can press the Tab key. If you want to get the same effect in theresults you present to the user, you can use the vbTab operator of the Visual Basic language.Here are examples:

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 46: Microsoft Visual Basic 2010 Tutorial

Sub Main() Dim FirstName Dim LastName Dim FullName

FirstName = "Francis " LastName = "Pottelson" FullName = LastName & ", " & FirstName

MsgBox("First Name: " & vbTab & FirstName & vbCrLf & "Last Name: " & vbTab & LastName & vbCrLf & "Full Name: " & vbTab & FullName)End Sub

This would produce:

In the same way, you can create as many vbTab combinations as necessary.

Unary Operators

Positive Unary Operator: +

Algebra uses a type of ruler to classify numbers. This ruler has a middle position of zero. Thenumbers on the left side of the 0 are referred to as negative while the numbers on the rightside of the rulers are considered positive:

-∞ -6 -5 -4 -3 -2 -1 1 2 3 4 5 6 +∞ 0

-∞ -6 -5 -4 -3 -2 -1 1 2 3 4 5 6 +∞

A value on the right side of 0 is considered positive. To express that a number is positive, youcan write a + sign on its left. Examples are +4, +228, +90335. In this case the + symbol iscalled a unary operator because it acts on only one operand.

The positive unary operator, when used, must be positioned on the left side of its operand,never on the right side.

As a mathematical convention, when a value is positive, you don't need to express it with the +operator. Just writing the number without any symbol signifies that the number is positive.Therefore, the numbers +4, +228, and +90335 can be, and are better, expressed as 4, 228,90335. Because the value does not display a sign, it is referred as unsigned.

The Negative Operator -

As you can see on the above ruler, in order to express any number on the left side of 0, itmust be appended with a sign, namely the - symbol. Examples are -12, -448, -32706. A valueaccompanied by - is referred to as negative.

The - sign must be typed on the left side of the number it is used to negate.

Remember that if a number does not have a sign, it is considered positive. Therefore, whenevera number is negative, it MUST have a - sign. In the same way, if you want to change a valuefrom positive to negative, you can just add a - sign to its left.

Arithmetic Operators

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 47: Microsoft Visual Basic 2010 Tutorial

Addition +

The addition is performed with the + sign. It is used to add one value to another.To add two numbers, such as 225 and 64, you could use 225 + 64. The result would be 289.The addition is also used to add the values of two variables as in MondayHours + TuesdayHoursto get a total number of hours worked on Monday and Tuesday.

Besides arithmetic operations, the + symbol can also be used to concatenate strings, that is, toadd one string to another. This is done by appending one string at the end of another. Here isan example:

Module Exercise Sub Main() Dim FirstName Dim LastName Dim FullName

FirstName = "James " LastName = "Fame" FullName = FirstName + LastName

MsgBox("Full Name: " & FullName) End SubEnd Module

Practical Learning: Using the Addition Operator

1. To use the addition, change the file as follows:

Module Training

Sub Main() Dim CustomerName Dim AccountNumber Dim InitialDeposit Dim RegularDeposit Dim TotalDeposits Dim Result

CustomerName = "Paul Bertrand Yamaguchi" AccountNumber = "52-92074-95" InitialDeposit = 325 RegularDeposit = 750 TotalDeposits = InitialDeposit + RegularDeposit

Result = " =-= Yugo National Bank =-=" & vbCrLf & "Customer Name: " & CustomerName & vbCrLf & "Account Number: " & AccountNumber & vbCrLf & "Total Deposits: $" & (InitialDeposit + RegularDeposit)

MsgBox(Result) End Sub

End Module

2. To execute the application, press F5

3. After using the program, return to your programming environment

Multiplication *

The multiplication operation allows you to add a number to itself a certain number of times setby another number. The multiplication operation is performed using the * sign. For example, toadd 25 to itself 3 times, you would perform the operation as 25 * 3

Subtraction -

The subtraction operation is performed using the - sign. This operation produces the differenceof two or more numbers. It could also be used to display a number as a negative value. Tosubtract 28 from 65, you express this with 65-28.

The subtraction can also be used to subtract the values of two values.

Practical Learning: Using the Subtraction Operator

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 48: Microsoft Visual Basic 2010 Tutorial

1. To subtract, change the file as follows:

Module Training

Sub Main() Dim CustomerName, AccountNumber Dim InitialDeposit, Withdrawals Dim RegularDeposit, TotalDeposits Dim CurrentBalance Dim Result

CustomerName = "Henriette Jolana" AccountNumber = "84-48662-72" InitialDeposit = 1500 RegularDeposit = 468.75 TotalDeposits = InitialDeposit + RegularDeposit Withdrawals = 300 CurrentBalance = TotalDeposits - Withdrawals

Result = " =-= Yugo National Bank =-=" & vbCrLf & "Customer Name: " & CustomerName & vbCrLf & "Account Number: " & AccountNumber & vbCrLf & "Total Deposits: $" & (InitialDeposit + RegularDeposit) & vbCrLf & "Withdrawals: $" & Withdrawals & vbCrLf & "Current Balance: $" & CurrentBalance

MsgBox(Result) End Sub

End Module

2. To execute the program, press F5

3. Return to your programming environment

Integer Division \

Dividing an item means cutting it in pieces or fractions of a set value. Therefore, the division isused to get the fraction of one number in terms of another. Microsoft Visual Basic provides twotypes of operations for the division. If you want the result of the operation to be a naturalnumber, called an integer, use the backlash operator "\" as the divisor. The formula to use is:

Value1 \ Value2

This operation can be performed on two types of valid numbers, with or without decimal parts.After the operation, the result would be a natural number.

Decimal Division /

The second type of division results in a decimal number. It is performed with the forward slash"/". Its formula is:

Value1 / Value2

After the operation is performed, the result is a decimal number.

Exponentiation ^

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 49: Microsoft Visual Basic 2010 Tutorial

Exponentiation is the ability to raise a number to the power of another number. This operationis performed using the ^ operator (Shift + 6). It uses the following formula:

yx

In Microsoft Visual Basic, this formula is written as:

y^x

and means the same thing. Either or both y and x can be values, variables, or expressions, butthey must carry valid values that can be evaluated. When the operation is performed, the valueof y is raised to the power of x.

Remainder: Mod

The division operation gives a result of a number with or without decimal values, which is fine insome circumstances. Sometimes you will want to get the value remaining after a divisionrenders a natural result.

The remainder operation is performed with keyword Mod. Its formula is:

Value1 Mod Value2

The result of the operation can be used as you see fit or you can display it in a control or beinvolved in another operation or expression.

Bit Operations

Introduction

From our introduction to variables, you may remember that the computer stores its data inmemory using small locations that look like boxes and each box contains a bit of information.Because a bit can be represented only either as 1 or 0, we can say that each box contains 1 or0. Bit manipulation consists of changing the value (1 or 0, or 0 or 1) in a box. As we will see inthe next few operations, it is not just about changing a value. It can involve reversing a valueor kind of "moving" a box from its current position to the next position.

The operations on bits are performed on 1s and 0s only. This means that any number isdecimal or hexadecimal format involved in a bit operation must be converted to binary first.

You will almost never perform some of the operations we are going to review. You will hardlyperform some other operations. There is only one operation you will perform on a regular basis.The OR operation is very regular in Microsoft Windows (Win32) programming so much that wewere obliged to include this whole section in the lesson, as opposed to mentioning only OR.

"Reversing" a Bit

Remember that, at any time, a box (or chunk) in memory contains either 1 or 0:

Bit reversal consists of reversing the value of a bit. If the box contains 1, you can reverse it to0. If it contains 0, you can reverse it to 1. To support this operation, the Visual Basic languageprovides the Not Operator.

As an example, consider the number 286. The decimal number 286 converted to binary is100011110. You can reverse each bit as follows:

286 1 0 0 0 1 1 1 1 0

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 50: Microsoft Visual Basic 2010 Tutorial

Not 286 0 1 1 1 0 0 0 0 1

Bitwise Conjunction

Bitwise conjunction consists of adding the content of one box (a bit) to the content of anotherbox (a bit). To support the bitwise conjunction operation, the Visual Basic language provides theAnd operator.

To perform the bit addition on two numbers, remember that they must be converted to binaryfirst. Then:

If a bit with value 0 is added to a bit with value 0, the result is 0 Bit0 0

Bit1 0

Bit0 AndBit1 0

If a bit with value 1 is added to a bit with value 0, the result is 0 Bit0 1

Bit1 0

Bit0 AndBit1 0

If a bit with value 0 is added to a bit with value 1, the result is 0 Bit0 0

Bit1 1

Bit0 AndBit1 0

If a bit with value 1 is added to a bit with value 1, the result is 1 Bit0 1

Bit1 1

Bit0 AndBit1 1

As an example, consider the number 286 bit-added to 475. The decimal number 286 convertedto binary is 100011110. The decimal number 4075 converted to binary is 111111101011. Basedon the above 4 points, we can add these two numbers as follows:

286 0 0 0 1 0 0 0 1 1 1 1 0

4075 1 1 1 1 1 1 1 0 1 0 1 1

286 And4075 0 0 0 1 0 0 0 0 1 0 1 0

Therefore, 286 And 4075 produces 100001010 which is equivalent to:

Bit8 Bit7 Bit6 Bit5 Bit4 Bit3 Bit2 Bit1 Bit0

256 128 64 32 16 8 4 2 1

286 And4075 1 0 0 0 0 1 0 1 0

256 0 0 0 0 8 0 2 0

This means that 286 And 4075 = 256 + 16 + 2 = 266

This can also be programmatically calculated as follows:

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 51: Microsoft Visual Basic 2010 Tutorial

Module Exercise

Sub Main() Dim Number1 = 286 Dim Number2 = 4075 Dim Result = Number1 And Number2

MsgBox("286 And 4075 = " & (Result)) End Sub

End Module

This would produce:

Bitwise Disjunction

Bitwise disjunction consists of disjoining one a bit from another bit. To support this operation,the Visual Basic language provides the Or operator.

To perform a bitwise conjunction on two numbers, remember that they must be converted tobinary first. Then:

If a bit with value 0 is added to a bit with value 0, the result is 0 Bit0 0

Bit1 0

Bit0 Or Bit1 0

If a bit with value 1 is added to a bit with value 0, the result is 1 Bit0 1

Bit1 0

Bit0 Or Bit1 1

If a bit with value 0 is added to a bit with value 1, the result is 1 Bit0 0

Bit1 1

Bit0 Or Bit1 1

If a bit with value 1 is added to a bit with value 1, the result is 1 Bit0 1

Bit1 1

Bit0 Or Bit1 1

As an example, consider the number 305 bit-disjoined to 2853. The decimal number 305converted to binary is 100110001. The decimal number 2853 converted to binary is101100100101. Based on the above 4 points, we can disjoin these two numbers as follows:

305 0 0 0 1 0 0 1 1 0 0 0 1

2853 1 0 1 1 0 0 1 0 0 1 0 1

305 Or 2853 1 0 1 1 0 0 1 1 0 1 0 1

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 52: Microsoft Visual Basic 2010 Tutorial

Therefore, 305 Or 2853 produces 101100110101 which is equivalent to:

Bit11 Bit10 Bit9 Bit8 Bit7 Bit6 Bit5 Bit4 Bit3 Bit2 Bit1 Bit0

2048 1024 512 256 128 64 32 16 8 4 2 1

305 Or 2853 1 0 1 1 0 0 1 1 0 1 0 1

2048 0 512 256 0 0 32 16 0 4 0 1

This means that 286 And 4075 = 2048 + 512 + 256 + 32 + 16 + 4 + 1 = 2869

This can also be programmatically calculated as follows:

Module Exercise

Sub Main() Dim Number1 = 305 Dim Number2 = 2853 Dim Result = Number1 Or Number2

MsgBox("286 Or 4075 = " & (Result)) End Sub

End Module

This would produce:

Bitwise Exclusion

Bitwise exclusion consists of adding two bits with the following rules. To support bitwiseexclusion, the Visual Basic language provides an operator named Xor:

If both bits have the same value, the result is 0 Bit0 0 1

Bit1 0 1

Bit0 XorBit1 0 0

If both bits are different, the result is 1 Bit0 0 1

Bit1 1 0

Bit0 XorBit1 1 1

As an example, consider the number 618 bit-excluded from 2548. The decimal number 618converted to binary is 1001101010. The decimal number 2548 converted to binary is100111110100. Based on the above 2 points, we can bit-exclude these two numbers as follows:

618 0 0 1 0 0 1 1 0 1 0 1 0

2548 1 0 0 1 1 1 1 1 0 1 0 0

618 Xor 2548 1 0 1 1 1 0 0 1 1 1 1 0

Therefore, 305 Or 2853 produces 101110011110 which is equivalent to:

Bit11 Bit10 Bit9 Bit8 Bit7 Bit6 Bit5 Bit4 Bit3 Bit2 Bit1 Bit0

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 53: Microsoft Visual Basic 2010 Tutorial

2048 1024 512 256 128 64 32 16 8 4 2 1

618 Xor 2548 1 0 1 1 1 0 0 1 1 1 1 0

2048 0 512 256 128 0 0 16 8 4 2 0

This means that 286 And 4075 = 2048 + 512 + 256 + 128 + 16 + 8 + 4 + 2 = 2974

This can also be programmatically calculated as follows:

Module Exercise

Sub Main() Dim Number1 = 618 Dim Number2 = 2548 Dim Result = Number1 Xor Number2

MsgBox("286 Xor 4075 = " & (Result)) End Sub

End Module

This would produce:

Left-Shifting the Bits

Left shifting the bits consists of pushing each bit from right to left. You can do this by one oremore bits. Once again, to perform this operation, the number has to be converted to its binaryequivalent. To support this operation, the Visual Basic language provides an operatorrepresented as <<.

Imagine you have a number as 741. Its binary equivalent is 1011100101 and can berepresented as:

1 0 1 1 1 0 0 1 0 1

To perform a left shift operation on these bits, you push each from its position to the left,depending on the number of pushes you want. For example, to left-shift by 1 bit, you pusheach bit to the left by one position. Actually, you consider the bit at position x and the bit to itsleft at position y. You replace the value of Bit y by the value of Bit x. If Bit x is the most rightbit, it receives a value of 0. This can be illustrated as follows:

Original 1 0 1 1 1 0 0 1 0 1

<< by 1 1 0 1 1 1 0 0 1 0 1 0

As a result, we get 10111001010. The decimal result can be calculated as follows:

Bit10 Bit9 Bit8 Bit7 Bit6 Bit5 Bit4 Bit3 Bit2 Bit1 Bit0

1024 512 256 128 64 32 16 8 4 2 1

741 << 1 1 0 1 1 1 0 0 1 0 1 0

1024 0 256 128 64 0 0 8 0 2 0

Consequently, 741 << 1 = 1024 + 256 + 128 + 64 + 8 + 2 = 458

This can also be evaluated programmatically as follows:

Module Exercise

Sub Main() MsgBox("741 << 1 = " & (741 << 1))

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 54: Microsoft Visual Basic 2010 Tutorial

End Sub

End Module

This would produce:

In the same way, you can push the bits to the left by more than one unit.

Right-Shifting the Bits

You can shift the bits to the right. Everything is done as reviewed for the left shift but inreverse order. To support this operation, the Visual Basic language provides the >> operator.

Application: Ending the Lesson

1. On the main menu, click File -> Close Solution (Microsoft Visual Studio) or File -> CloseProject (Microsoft Visual Basic 2010 Express)

2. When asked whether you want to save, click Discard

Previous Copyright © 2008-2010 FunctionX Next

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 55: Microsoft Visual Basic 2010 Tutorial

Introduction to Variables

Variable Declaration With Type

Introduction

As we will see in the next lessons, when a user is asked to provide a value in a program, thevalue is primarily considered a normal group of characters, also called a string. If you intendto involve that value in an operation that is not meant for a string, you should (usually must)first convert that string to the appropriate value. Fortunately, each data type that we aregoing to review presents an appropriate and easy mechanism to perform this conversion.

To specify the amount of memory that a variable would use, on the right side of the variable'sname, you type the As keyword followed by the data type. The formula to declare such avariable is:

Dim VariableName As DataType

Type Characters

To make variable declaration a little faster and even convenient, you can replace the AsDataType expression with a special character that represent the intended data type. Such acharacter is called a type character and it depends on the data type you intend to apply to avariable. When used, the type character must be the last character of the name of thevariable. We will see what characters are available and when it can be applied.

Numeric Data Types

Introduction

A natural number is one that contains either only one digit or a combination of digits and no other character, exceptthose added to make it easier to read. Examples of natural numbers are 122 and 2864347. When a natural number istoo long, such 3253754343, to make it easier to read, the thousands are separated by a special character. Thischaracter depends on the language or group of languages and it is called the thousands separator. For US English, thischaracter is the comma. The thousands separator symbol is used only to make the number easier to read. You willnever use it in your code when referring to a number.

To support different scenarios, Visual Basic provides different types of natural numbers.

Practical Learning: Introducing Variables

1. Start Microsoft Visual Basic 2010 Express or Microsoft Visual Studio 2010

From now on, we will only refer to Microsoft Visual Basic

2. To create a new application, on the Start Page, click New Project...

3. In the middle list, click Console Application

4. In the Name text box, replace the name with GeorgetownDryCleaningServices1

5. Click OK

6. In the Solution Explorer, right-click Module1.vb and click Rename

7. Type CleaningOrder.vb and press Enter

8. On the main menu, click Project -> GeorgetownDryCleaningServices1 Properties

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 56: Microsoft Visual Basic 2010 Tutorial

9. Click the arrow of the Application Type box and select Windows Forms Application

10. Click the Close button to close the Property Pages window

A Byte

A byte is a group of 8 bits. Since each bit can have a value or either 1 or 0. The total number of possible combinationsof 8 bits is 27 + 26 + 25 + 24 + 23 + 22 + 21 + 20 = 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 255. Since all bits canhave values of 0 each, a byte can have values from 0 to 255. Therefore, a byte can hold a small natural positivenumber that ranges from 0 to 255.

To declare a variable for a small number, use the Byte keyword. Here is an example:

Module Exercise

Sub Main() Dim StudentAge As Byte End Sub

End Module

A Byte variable is initialized with 0. Otherwise, to initialize it, you can assign it a small number from 0 to 255. Toconvert a value to a Byte value, you can use CByte(). To do this, enter the value or the expression in the parenthesesof CByte(). If the conversion is successful, CByte() produces a Byte value.

There is no type character for the Byte data type.

Practical Learning: Using Bytes

1. Change the CleaningOrder.vb file as follows:

Module GeorgetownDryCleaner

Sub Main() Dim Shirts As Byte Dim Pants As Byte

Shirts = InputBox("Enter Number of Shirts") Pants = InputBox("Enter Number of Pants")

MsgBox("-/- Georgetown Cleaning Services -/-" & vbCrLf & "======================" & vbCrLf & "Item Type" & vbTab & "Qty" & vbCrLf & "--------------------------------------------" & vbCrLf & "Shirts " & vbTab & vbTab & Shirts & vbCrLf & "Pants " & vbTab & vbTab & Pants & vbCrLf & "======================") End Sub

End Module

2. To execute the program, on the main menu, click Debug -> Start Debugging

3. Enter the number of shirts as 4 and the number of pants as 2. This would produce:

4. Click OK to close the message box

A Signed Byte

If you want to use a very small number but it does not have to be positive, the Visual Basic language provides analternative. A signed byte is a small number that is between -127 and 128. To declare a variable for such a number,

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 57: Microsoft Visual Basic 2010 Tutorial

you can use the SByte data type. This can be done as follows:

Module Exercise

Sub Main() Dim Temperature As SByte End Sub

End Module

To convert a value to an SByte value, use CSByte().

There is no type character for the SByte data type.

A Short Integer

An integer is a natural number larger than the Byte. Examples of such ranges are the number of pages of a book, theage of a person. To declare a variable that can hold natural numbers in the range of -32768 to 32767, you can use theShort data type.

Here is an example:

Module Exercise

Sub Main() Dim MusicTracks As Short End Sub

End Module

By default, a Short variable is initialized with 0. After declaring a Short variable, you can initialize it with the necessaryvalue that must be a relatively small integer from -32768 to 32767. Here is an example:

Module Exercise

Sub Main() Dim MusicTracks As Short

MusicTracks = 16 MsgBox(MusicTracks) End Sub

End Module

In some cases, the compiler may allocate more memory than the variable needs, beyond the area required by a Shortvalue. To indicate that the number must be treated as a Short and not another type of value, type s or S on the rightof the initializing value. Here is an example:

Module Exercise

Sub Main() Dim MusicTracks As Short

MusicTracks = 16S MsgBox("This album contains " & MusicTracks & " tracks.") End Sub

End Module

This would produce:

To convert a value to a short integer, you can use CShort() by entering the value or the expression in the parenthesesof CShort(). If the conversion is successful, CShort() produces a Short value.

There is no type character for the Short data type.

An Unsigned Short Integer

As mentioned above, a short integer can be either negative or positive. If you want to use a relatively small number

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 58: Microsoft Visual Basic 2010 Tutorial

that must be positive, you must store it as an unsigned short integer. An unsigned short integer is a natural numberbetween 0 and 65535.

To declare a variable that would hold a short positive number, you can use the UShort data type. Here is an example:

Module Exercise

Sub Main() Dim TotalNumberOfStudents As UShort End Sub

End Module

There is no type character for the UShort data type.

To convert something to an unsigned short integer, put in the parentheses of CUShort().

Practical Learning: Using Unsigned Short Integers

1. To use unsigned short integers, change the file as follows:

Module GeorgetownDryCleaner

Sub Main() Dim Shirts As Byte Dim Pants As Byte Dim OtherItems As UShort

Shirts = InputBox("Enter Number of Shirts") Pants = InputBox("Enter Number of Pants") OtherItems = InputBox("Enter Number of Other Items")

MsgBox("-/- Georgetown Cleaning Services -/-" & vbCrLf & "======================" & vbCrLf & "Item Type" & vbTab & "Qty" & vbCrLf & "--------------------------------------------" & vbCrLf & "Shirts " & vbTab & vbTab & Shirts & vbCrLf & "Pants " & vbTab & vbTab & Pants & vbCrLf & "Other Items " & vbTab & OtherItems & vbCrLf & "======================") End Sub

End Module

2. To execute the program, on the main menu, click Debug -> Start Debugging

3. Enter the number of shirts as 2, the number of pants as 5, and the number of other items as 3. This wouldproduce:

4. Click OK to close the message box

An Integer

If you want a variable to hold values larger than the Short data type can accommodate, you can use the Integer datatype to declare it. A variable declared with the Integer data type can hold a value between -2,147,483,648 and2,147,483,647. Here is an example:

Module Exercise

Sub Main() Dim NumberOfPages As Integer End Sub

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 59: Microsoft Visual Basic 2010 Tutorial

End Module

Alternatively, you can use the % type character to declare an integral variable. Here is an example:

Module Exercise

Sub Main() Dim NumberOfPages% End Sub

End Module

To convert a value to an integer, use CInt(): enter the value or the expression in the parentheses of CInt(). If theconversion is successful, CInt() produces an integral value.

After declaring an Integer variable, the compiler initializes it with a 0 value. Still, you can initialize it with thenecessary value but you have three or four alternatives. To initialize the variable with a regular natural number, youcan simply assign it that number. Here is an example:

Module Exercise

Sub Main() Dim NumberOfPages As Integer

NumberOfPages = 846 MsgBox("This book contains " & NumberOfPages & " pages.") End Sub

End Module

This would produce:

The Visual Basic language considers three types of integer values. Instead of just assigning a regular natural number,to indicate that the value must be considered as an integer, you can enter i or I on the right side of the value. Here isan example:

Module Exercise

Sub Main() Dim NumberOfPages As Integer

NumberOfPages = 846I End Sub

End Module

The second type of integral number is referred to as hexadecimal. On a surface, it is primarily a different way ofrepresenting a number by using a combination of 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f, A, B, C, D, E, or F. This stillallows you to represent any natural number. To initialize an integer variable with a hexadecimal number, start the valuewith &h or &H. Here is an example:

Module Exercise

Sub Main() Dim NumberOfStudents As Integer

NumberOfStudents = &H4A26EE MsgBox("School Current Enrollment: " & NumberOfStudents & " students.") End Sub

End Module

This would produce:

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 60: Microsoft Visual Basic 2010 Tutorial

Besides the regular natural or the hexadecimal numbers, the third type of value an Integer variable can hold isreferred to as octal. This is a technique used to represent a natural number using a combination of 0, 1, 2, 3, 4, 5, 6,and 7. To use such a value, start it with &o or &O (the letter O and not the digit 0). Here is an example:

Module Exercise

Sub Main() Dim NumberOfStudents As Integer

NumberOfStudents = &O4260 MsgBox("School Current Enrollment: " & NumberOfStudents & " students.") End Sub

End Module

This would produce:

An Unsigned Integer

We saw that the Integer data type is used to declare a variable for a large number that can be negative or positive. Ifyou want the number to only be positive, you can declare it as an unsigned integer. An unsigned integer is a numberbetween 0 and 4294967295. Examples are the population of a city, the distance between places of different countries,the number of words of a book.

To declare a variable that can a large positive number, use the UInteger data type. Here is an example:

Module Exercise

Sub Main() Dim Population As UInteger End Sub

End Module

You can initialize the variable using a positive integer in decimal, hexadecimal, or octal format.

To convert a value to an unsigned short integer, use CUInt() by entering the value or the expression in theparentheses.

There is no type character for the UInteger data type.

A Long Integer

A long integer is a very large natural number that is between -9,223,372,036,854,775,808 and9,223,372,036,854,775,807. To declare a variable that can hold a very large natural number, use the Long data type.Here is an example:

Module Exercise

Sub Main() Dim Population As Long

End Sub

End Module

Instead of the AS Long expression, as an alternatively, you can also use the @ symbol as the type character to declarea Long variable. Here is an example:

Module Exercise

Sub Main() Dim Population@ End Sub

End Module

To convert a value to a long integer, you can use CLng(). To do this, enter the value or the expression in the

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 61: Microsoft Visual Basic 2010 Tutorial

parentheses of CLng(). If the conversion is successful, CLng() produces a Long integer value.

Like all integers, a Long variable is initialized, by default, with 0. After declaring a Long variable, you can initialize withthe necessary natural number. Here is an example:

Module Exercise

Sub Main() Dim Population@

Population@ = 9793759 MsgBox("Country Population: " & Population) End Sub

End Module

This would produce:

To indicate that the value must be treated as Long, type l or L on the right side of the number. Here is an example:

Module Exercise

Sub Main() Dim Population@

Population@ = 9793759L End Sub

End Module

Because Long is primarily an integral like the Integer data type we reviewed earlier, you can also initialize it using adecimal, a hexadecimal, or an octal value. Here is an example of a variable initialized with a hexadecimal value:

Module Exercise

Sub Main() Dim Population@

Population = &HFF42AD MsgBox("Country Population: " & Population) End Sub

End Module

This would produce:

An Unsigned Long Integer

We saw that a long integer can be a very large negative or positive natural number. If you want to store a very largenumber but the number but be positive, you can consider it as an unsigned long integer. Such a number can bebetween 0 and 18446744073709551615.

To declare a variable that can hold a very large natural positive number, use the ULong data type. Here is an example:

Module Exercise

Sub Main() Dim DistanceBetweenBothPlanets As ULong

End Sub

End Module

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 62: Microsoft Visual Basic 2010 Tutorial

There is no type character for the ULong data type.

To convert a value to an unsigned long integer, use CULng().

Floating-Point Numbers

Introduction

A real number is one that displays a decimal part. This means that the number can be made of two sections separatedby a symbol that is referred to as the Decimal Separator or Decimal Symbol. This symbol is different by language,country, group of languages, or group of countries. In US English, this symbol is the period as can be verified from theRegional (and Language) Settings of the Control Panel of computers of most regular users:

On both sides of the Decimal Symbol, digits are used to specify the value of the number. The number of digits on theright side of the symbol determines how much precision the number offers.

Practical Learning: Introducing Decimal Variables

1. To add a project, on the main menu, click File -> Add -> New Project...

2. In the middle list, click Console Application

3. Set the Name to YugoNationalBank1 and click OK

4. In the Solution Explorer, under YugoNationalBank1, right-click Module1.vb and click Rename

5. Type YugoNationalBank.vb and press Enter

Single-Precision

A decimal number is said to have single precision if it can include a decimal part but the precision of the number is notimportant. In the Visual Basic language, such a number has a value that can range from -3.402823e38 and -1.401298e-

45 if the number is negative, or 1.401298e-45 and 3.402823e38 if the number is positive.

To declare a variable that can hold small decimal numbers with no concern for precision, use the Single data type.Here is an example:

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 63: Microsoft Visual Basic 2010 Tutorial

Module Exercise

Sub Main() Dim Distance As Single End Sub

End Module

Instead of the AS Single expression, you can use the ! symbol as the type character. Here is an example:

Module Exercise

Sub Main() Dim Distance! End Sub

End Module

The ! symbol can also be used in other scenarios in the Visual Basic language. Whenever you use it, make sure theword that comes to its right is not the name of a variable.

A Single variable is initialized with 0. After declaring a Single variable, you can declare it with the necessary value.Here is an example:

Module Exercise

Sub Main() Dim Distance!

Distance! = 195.408 MsgBox("Distance: " & Distance) End Sub

End Module

This would produce:

In some cases, the compiler may allocate more memory than necessary for the variable. For example, the above valueis more suitable for another type as we will see in the next section. Otherwise, to indicate that the variable must betreated as a decimal number with single-precision, type f or F on the right side of the number. Here is an example:

Module Exercise

Sub Main() Dim Distance!

Distance! = 195.408f End Sub

End Module

To convert a string to a long integer, call CSng(). Enter the value or the expression in the parentheses of CSng(). Ifthe conversion is successful, CSng() produces a Single value.

Double-Precision

While the Single data type can allow large numbers, it offers less precision. For an even largernumber, Visual Basic provides the Double data type. This is used for a variable that would holdnumbers that range from 1.79769313486231e308 to 4.94065645841247e324 if the number isnegative or from 1.79769313486231E308 to 4.94065645841247E324 if the number is positive.

To declare a variable that can store large decimal numbers with a good level of precision, use theDouble keyword.

In most circumstances, it is preferable to use Double instead of Single when declaring avariable that would hold a decimal number. Although the Double takes more memoryspaces (computer memory is not expensive anymore(!)), it provides more precision.

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 64: Microsoft Visual Basic 2010 Tutorial

Here is an example of declaring a Double variable:

Module Exercise

Sub Main() Dim TempFactor As Double End Sub

End Module

If you want, you can omit the AS Double expression but use the # symbol instead to declare aDouble variable. This can be done as follows:

Module Exercise

Sub Main() Dim TempFactor# End Sub

End Module

A double-precision variable is initialized with a 0 value. After declaring a Double variable, you caninitialize it with the needed value. Here is an example:

Module Exercise

Sub Main() Dim TempFactor#

TempFactor# = 482 MsgBox("Temperature: " & TempFactor & " Degrees") End Sub

End Module

This would produce:

To indicate that the variable being used must be treated with double precision, enter r or R on itsright side. Here is an example:

Module Exercise

Sub Main() Dim TempFactor#

TempFactor# = 482r MsgBox("Temperature: " & TempFactor & " Degrees") End Sub

End Module

To convert a value to a double-precision number, call CDbl() by entering the value or theexpression in the parentheses of CDbl(). If CDbl() succeeds, it produces a Double value.

Practical Learning: Using Double Precision Variables

1. To use the double-precision variables, change the YugoNationalBank.vb file as follows:

Module YugoNationalBank

Sub Main() Dim CustomerName Dim AccountNumber Dim InitialDeposit Dim Withdrawals Dim CurrentBalance Dim Result Dim strDeposit, strWithdrawals

CustomerName = InputBox("Enter Customer Name:") AccountNumber = InputBox("Enter Account #:")

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 65: Microsoft Visual Basic 2010 Tutorial

strDeposit = InputBox("Enter Initial Deposit:") strWithdrawals = InputBox("Enter total withdrawals:")

InitialDeposit = CDbl(strDeposit) Withdrawals = CDbl(strWithdrawals) CurrentBalance = InitialDeposit - Withdrawals

Result = " =-= Yugo National Bank =-=" & vbCrLf & "Customer Name: " & vbTab & CustomerName & vbCrLf & "Account Number: " & vbTab & AccountNumber & vbCrLf & "Deposits: " & vbTab & InitialDeposit & vbCrLf & "Withdrawals: " & vbTab & Withdrawals & vbCrLf & "Current Balance: " & vbTab & CurrentBalance

MsgBox(Result) End Sub

End Module

2. To execute the program, press F5

3. Enter the requested values. Here are examples:

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 66: Microsoft Visual Basic 2010 Tutorial

4. When you have finished, click the OK button

Decimal

The decimal data type can be used to declare a variable that would hold significantly large valuesthat can be stored in a combination of 128 bits. You declare such a variable using the Decimalkeyword. The values stored in a decimal variable can range from ±1.0 x 10−28 to ±7.9 x 1028

with a precision of 28 to 29 digits. Because of this high level of precision, the Decimal data typeis suitable for currency values.

Like those of the other numeric types, by default, a variable declared as Decimal is initialized with0. After declaring a decimal variable, you can initialize it with a natural number. To indicate to thecompiler to reserve space enough to store a decimal value, add a d or D to the right side of thevalue. Here is an example:

Module Exercise

Sub Main() Dim DistanceBetweenPlanets As Decimal

DistanceBetweenPlanets = 592759797549D End Sub

End Module

To convert a value or an expression to Decimal, you can call CDec().

Characters and Strings

Characters

A character can be a letter, a digit, any readable or non-readable symbol that can be represented.To declare a variable that would hold a character, use the Char data type. Here is an example:

Module Exercise

Sub Main() Dim Letter As Char End Sub

End Module

When declaring a Char variable, if you don't initialize it, the compiler does it with an emptycharacter. Otherwise, after declaring a Char variable, you can initialize it with a single characterincluded in double-quotes. Here is an example:

Module Exercise

Sub Main() Dim Letter As Char

Letter = "W" End Sub

End Module

To indicate that the value of the variable must be treated as Char, when initializing it, you cantype c or C on the right side of the double-quoted value. Here is an example:

Module Exercise

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 67: Microsoft Visual Basic 2010 Tutorial

Sub Main() Dim Letter As Char

Letter = "W"c End Sub

End Module

To convert a value to Char, you can call CChar().

Strings

A string is an empty text, a letter, a word or a group of words considered "as is". To declare astring variable, you can use the String data type. Here is an example:

Module Exercise

Sub Main() Dim Sentence As String End Sub

End Module

If you want, you can replace the AS String expression with the $ symbol when declaring a stringvariable. This can be done as follows:

Module Exercise

Sub Main() Dim Sentence$ End Sub

End Module

After declaring a String variable, by default, the compiler initializes it with an empty string.Otherwise, you can initialize it with a string of your choice. To do this, include the string betweendouble quotes. Here is an example:

Module Exercise

Sub Main() Dim Sentence$

Sentence$ = "He called me" End Sub

End Module

If you want to include a double-quote character in the string, you can double it. Here is anexample:

Module Exercise

Sub Main() Dim Sentence$

Sentence$ = "Then she said, ""I don't love you no more."" and I left" MsgBox(Sentence) End Sub

End Module

This would produce:

To convert a value to a string, call CStr() and enter the value or the expression in itsparentheses. If the value is an appropriate date or time, CStr() would produces a string thatrepresents that date or that time value.

Practical Learning: Using Strings

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 68: Microsoft Visual Basic 2010 Tutorial

1. Continue with the YugoNationalBank1 application.To use a few string variables, change the program as follows:

Module YugoNationalBank

Sub Main() Dim CustomerName As String Dim AccountNumber As String Dim InitialDeposit As Double Dim Withdrawals As Double Dim CurrentBalance As Double Dim Result As String Dim strDeposit As String, strWithdrawals As String

CustomerName = InputBox("Enter Customer Name:") AccountNumber = InputBox("Enter Account #:") strDeposit = InputBox("Enter Initial Deposit:") strWithdrawals = InputBox("Enter total withdrawals:")

InitialDeposit = CDbl(strDeposit) Withdrawals = CDbl(strWithdrawals) CurrentBalance = InitialDeposit - Withdrawals

Result = " =-= Yugo National Bank =-=" & vbCrLf & "Customer Name: " & vbTab & CustomerName & vbCrLf & "Account Number: " & vbTab & AccountNumber & vbCrLf & "Deposits: " & vbTab & InitialDeposit & vbCrLf & "Withdrawals: " & vbTab & Withdrawals & vbCrLf & "Current Balance: " & vbTab & CurrentBalance

MsgBox(Result) End Sub

End Module

2. To execute the application, press F5

3. Provide the requested values. Here is an example:

4. Close the message box and return to your programming environment

Dates and Times

A date is a numeric value that represents the number of days that have elapsed since adetermined period. A time is a numeric value that represents the number of seconds that haveelapsed in a day.

To declare a variable that can hold either date values, time values, or both, you can use the Datedata type. After the variable has been declared, you will configure it to the appropriate value. Hereare two examples:

Module Exercise Sub Main() Dim DateOfBirth As Date Dim KickOffTime As Date End SubEnd Module

As mentioned above, the Date data type is used for both date and time. Like the other values,there are rules you must observe when dealing with date and time values. The rules are defined inthe Regional Settings Properties of the Control Panel of the computer on which the application isrun. The rules for the dates are defined in the Date property page:

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 69: Microsoft Visual Basic 2010 Tutorial

The rules for the time values are defined in the Time property page:

When using date and time values in your applications, you should not change these rules becausethe application will refer to them when it is installed in someone else's computer.

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 70: Microsoft Visual Basic 2010 Tutorial

By default, a Date variable is initialized with January 1st, 0001 at midnight as the starting value.After declaring a Date variable, you can initialize it with an appropriate date or time or date andtime value. The value can be included in double-quotes. Here is an example:

Module Exercise

Sub Main() Dim DateOfBirth As Date

DateOfBirth = "08/14/1982" MsgBox("Date of Birth: " & DateOfBirth) End Sub

End Module

This would produce:

If you intend to use only a date value for a Date variable, its corresponding time part would be setto midnight of the same date. Based on this, the above program would produce:

8/14/1982 12:00:00 AM

If you intend to use only a time value for your Date variable, the date part of the variable wouldbe set to January 1st, 0001.

A Date value can also be included between two # signs. Here is an example:

Module Exercise

Sub Main() Dim DateOfBirth As Date Dim KickOffTime As Date

DateOfBirth = "08/14/1982" KickOffTime = #6:45:00 PM# MsgBox("Date of Birth: " & DateOfBirth) MsgBox("Kick off Time: " & KickOffTime) End Sub

End Module

To convert a value to a date or a time value, write an appropriate date or a recognizable time inthe parentheses of CDate(). If the value is appropriate, CDate() produces a Date value.

Practical Learning: Using Date and Time Variables

1. In the Solution Explorer, under GeorgetownDryCleaner1, double-click CleaningOrder.vb

2. To deal with new dates and times, change the program as follows:

Module GeorgetownDryCleaner

Sub Main() Dim CustomerName As String, CustomerPhone As String Dim OrderDate As Date, OrderTime As Date ' Unsigned numbers to represent cleaning items Dim NumberOfShirts As UInteger, NumberOfPants As UInteger Dim NumberOfOtherItems As UInteger ' Each of these sub totals will be used for cleaning items Dim SubTotalShirts As Double, SubTotalPants As Double Dim SubTotalOtherItems As Double ' Values used to process an order Dim TotalOrder As Double, TaxAmount As Double Dim NetTotal As Double Dim AmountTended As Double, Difference As Double

' Request order information from the user CustomerName = InputBox("Enter Customer Name:") CustomerPhone = InputBox("Enter Customer Phone:") OrderDate = InputBox("Enter the order date:") OrderTime = InputBox("Enter the order time:")

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 71: Microsoft Visual Basic 2010 Tutorial

3. To execute the program, on the main menu, click Debug -> Start Debugging

4. Enter the number of shirts as 6, the number of pants as 4, and the number of other items as2

5. Enter the amount tended as 30.Here is an example:

NumberOfShirts = InputBox("Enter Number of Shirts") NumberOfPants = InputBox("Enter Number of Pants") NumberOfOtherItems = InputBox("Enter Number of Other Items")

' Perform the necessary calculations SubTotalShirts = NumberOfShirts * 1.15 SubTotalPants = NumberOfPants * 1.95 SubTotalOtherItems = NumberOfOtherItems * 3.25 ' Calculate the "temporary" total of the order TotalOrder = SubTotalShirts + SubTotalPants + SubTotalOtherItems

' Calculate the tax amount using a constant rate TaxAmount = TotalOrder * 0.0575 ' Add the tax amount to the total order NetTotal = TotalOrder + TaxAmount

' Communicate the total to the user... MsgBox("The Total order is: " & NetTotal) ' and request money for the order AmountTended = InputBox("Amount Tended?")

MsgBox(vbTab & "-/- Georgetown Dry Cleaner -/-" & vbCrLf & "==============================" & vbCrLf & vbTab & "Customer Name: " & CustomerName & vbCrLf & vbTab & "Customer Phone: " & CustomerPhone & vbCrLf & vbTab & "Order Date: " & OrderDate & vbCrLf & vbTab & "Order Time: " & OrderTime & vbCrLf & "------------------------------------------------------------" & vbCrLf & "Item Type" & vbTab & "Qty" & vbTab & "Unit/Price" & vbTab & "Sub-Total" & vbCrLf & "------------------------------------------------------------" & vbCrLf & "Shirts " & vbTab & vbTab & CStr(NumberOfShirts) & vbTab & "1.15" & vbTab & CStr(SubTotalShirts) & vbCrLf & "Pants " & vbTab & vbTab & CStr(NumberOfPants) & vbTab & "1.95" & vbTab & CStr(SubTotalPants) & vbCrLf & "Other Items " & vbTab & CStr(NumberOfOtherItems) & vbTab & "3.25" & vbTab & CStr(SubTotalOtherItems) & vbCrLf & "-----------------------------------------------------------" & vbCrLf & vbTab & "Total Cleaning: " & vbTab & CStr(TotalOrder) & vbCrLf & vbTab & "Tax Rate: " & vbTab & "5.75%" & vbCrLf & vbTab & "Tax Amount: " & vbTab & CStr(TaxAmount) & vbCrLf & vbTab & "Net Price: " & vbTab & CStr(NetTotal) & vbCrLf & "==============================") End Sub

End Module

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 72: Microsoft Visual Basic 2010 Tutorial

6. Click OK and return to your programming environment

Object

An Object can be any type of data that you want to use in your program. In most cases, butsparingly, it can be used to declare a variable of any type. Here are examples:

Module Exercise

Sub Main() Dim CountryName As Object Dim NumberOfPages As Object Dim UnitPrice As Object

CountryName = "Australia" NumberOfPages = 744 UnitPrice = 248.95

MsgBox("Country Name: " & CountryName) MsgBox("Number of Pages: " & NumberOfPages) MsgBox("Unit Price: " & UnitPrice) End Sub

End Module

If you do not specify a data type or cannot figure out what data type you want to use, you can usethe Object data type. As you can see from the result of the above program, the vbc compilerknows how to convert the value of any Object variable to the appropriate type. On the otherhand, to convert a value or an expression to the Object type, you can use CObj().

Application: Ending the Lesson

1. On the main menu, click File -> Close Solution (Microsoft Visual Studio) or File -> CloseProject (Microsoft Visual Basic 2010 Express)

2. When asked whether you want to save, click Discard

Previous Copyright © 2008-2010 FunctionX Next

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 73: Microsoft Visual Basic 2010 Tutorial

Using Variables

Constants

Introduction

A constant is a value that doesn't change. There are two types of constants you will use inyour programs: those supplied to you and those you define yourself.

To create a constant to use in your program type the Const keyword followed by a name forthe variable, followed by the assignment operator "=", and followed by the value that theconstant will hold. Here is an example:

Module Exercise Sub Main() Const DateOfBirth = #12/5/1974#

MsgBox(DateOfBirth) End SubEnd Module

When defining a constant like this, the compiler would know the type of data to apply to thevariable. In this case the DateOfBirth constant holds a Date value. Still, to be more explicit,you can indicate the type of value of the constant by following its name with the As keywordand the desired data type. Based on this, the above program would be:

Module Exercise Sub Main() Const DateOfBirth As Date = #12/5/1974#

MsgBox("Date of Birth: " & DateOfBirth) End SubEnd Module

When creating a constant, if its value supports a type character, instead of using the As keyword, you can use thattype character. Here is an example:

Module Exercise

Sub Main() Const Temperature% = 52 End Sub

End Module

As mentioned earlier, the second category of constants are those that are built in the Visual Basic language. Becausethere are many of them and used in different circumstances, when we need one, we will introduce and then use it.

Practical Learning: Using Constants

1. Start Microsoft Visual Basic

2. To create a new application, on the Start Page, click New Project...

3. In the middle list, click Console Application

4. In the Name text box, replace the name with GeorgetownDryCleaningServices2

5. Click OK

6. In the Solution Explorer, under GeorgetownDryCleaner2, right-click Module1.vb and click Rename

7. Type CleaningOrder.vb and press Enter

8. To deal with new dates and times, change the program as follows:

Module CleaningOrder

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 74: Microsoft Visual Basic 2010 Tutorial

9. On the main menu, click Project -> GeorgetownDryCleaningServices2 Properties

10. Click the arrow of the Application Type box and select Windows Forms Application

11. Click the Close button to close the Property Pages window

12. To execute the program, on the main menu, click Debug -> Start Debugging

13. Enter values as follows: Customer Name: Jeannette Sharma

Sub Main() Const UnitPriceShirts As Double = 1.25 Const UnitPricePants As Double = 1.95 Const UnitPriceOtherItems As Double = 3.25 Const TaxRate As Double = 5.75

Dim CustomerName As String, CustomerPhone As String Dim OrderDate As Date, OrderTime As Date ' Unsigned numbers to represent cleaning items Dim NumberOfShirts As UInteger, NumberOfPants As UInteger Dim NumberOfOtherItems As UInteger ' Each of these sub totals will be used for cleaning items Dim SubTotalShirts As Double, SubTotalPants As Double Dim SubTotalOtherItems As Double ' Values used to process an order Dim TotalOrder As Double, TaxAmount As Double Dim NetTotal As Double Dim AmountTended As Double

' Request order information from the user CustomerName = InputBox("Enter Customer Name:") CustomerPhone = InputBox("Enter Customer Phone:") OrderDate = InputBox("Enter the order date:") OrderTime = InputBox("Enter the order time:")

NumberOfShirts = InputBox("Enter Number of Shirts") NumberOfPants = InputBox("Enter Number of Pants") NumberOfOtherItems = InputBox("Enter Number of Other Items")

' Perform the necessary calculations SubTotalShirts = NumberOfShirts * UnitPriceShirts SubTotalPants = NumberOfPants * UnitPricePants SubTotalOtherItems = NumberOfOtherItems * UnitPriceOtherItems ' Calculate the "temporary" total of the order TotalOrder = SubTotalShirts + SubTotalPants + SubTotalOtherItems

' Calculate the tax amount using a constant rate TaxAmount = TotalOrder * TaxRate / 100 ' Add the tax amount to the total order NetTotal = TotalOrder + TaxAmount

' Communicate the total to the user... MsgBox("The Total order is: " & NetTotal) ' and request money for the order AmountTended = InputBox("Amount Tended?")

MsgBox(vbTab & "-/- Georgetown Dry Cleaner -/-" & vbCrLf & "==============================" & vbCrLf & vbTab & "Customer Name: " & CustomerName & vbCrLf & vbTab & "Customer Phone: " & CustomerPhone & vbCrLf & vbTab & "Order Date: " & OrderDate & vbCrLf & vbTab & "Order Time: " & OrderTime & vbCrLf & "------------------------------------------------------------" & vbCrLf & "Item Type" & vbTab & "Qty" & vbTab & "Unit/Price" & vbTab & "Sub-Total" & vbCrLf & "------------------------------------------------------------" & vbCrLf & "Shirts " & vbTab & vbTab & CStr(NumberOfShirts) & vbTab & CStr(UnitPriceShirts) & vbTab & CStr(SubTotalShirts) & vbCrLf & "Pants " & vbTab & vbTab & CStr(NumberOfPants) & vbTab & CStr(UnitPricePants) & vbTab & CStr(SubTotalPants) & vbCrLf & "Other Items " & vbTab & CStr(NumberOfOtherItems) & vbTab & CStr(UnitPriceOtherItems) & vbTab & CStr(SubTotalOtherItems) & vbCrLf & "-----------------------------------------------------------" & vbCrLf & vbTab & "Total Cleaning: " & vbTab & CStr(TotalOrder) & vbCrLf & vbTab & "Tax Rate: " & vbTab & CStr(TaxRate) & "%" & vbCrLf & vbTab & "Tax Amount: " & vbTab & CStr(TaxAmount) & vbCrLf & vbTab & "Net Price: " & vbTab & CStr(NetTotal) & vbCrLf & "==============================") End Sub

End Module

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 75: Microsoft Visual Basic 2010 Tutorial

Customer Phone: (301) 218-9000

Order Date: 04/11/2008

Order Time 08:24

Number of Shirts: 6

Number of Pants: 4

Number of Other Items: 2

14. Enter the amount tended as 40

15. Close the message box and return to your programming environment

Nothing

So far, to initialize a variable, we were using a known value. Alternatively, you can use the Nothing constant toinitialize a variable, simply indicating that it holds a value that is not (yet) defined. Here is an example:

Module Exercise

Sub Main() Dim DateOfBirth As Date = Nothing End Sub

End Module

If you use the Nothing keyword to initialize a variable, the variable is actually initialized to the default value of itstype. For example, a number would be assigned 0, a date would be assigned January 1, 0001 at midnight.

The Scope and Lifetime of a Variable

Local Variables

The scope of a variable determines the areas of code where the variable is available. You may have noticed that, so far,we declared all our variables only inside of Main(). Actually, the Visual Basic language allows you to declare variablesoutside of Main() (and outside of a particular procedure).

A variable declared inside of a procedure such as Main() is referred to as a local variable. Such as variable cannot beaccessed by another part (such as another procedure) of the program.

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 76: Microsoft Visual Basic 2010 Tutorial

Global Variables

A variable that is declared outside of any procedure is referred to as global. To declare a global variable, use the sameformula as we have done so far. For example, just above the Sub Main() line, you can type Dim, followed by thename of the variable, the As keyword, its type and an optional initialization. Here is an example:

Module Exercise

Dim DateOfBirth As Date

Sub Main() End Sub

End Module

As mentioned above, you can initialize the global variable when or after declaring it. Here are two examples:

Module Exercise

Dim UnitPrice As Double Dim DateOfBirth As Date = #12/5/1974#

Sub Main() UnitPrice = 24.95 MsgBox("Date of Birth: " & DateOfBirth) MsgBox("Unit Price: " & UnitPrice) End Sub

End Module

As we will see when studying procedures, a global variable can be accessed by any other procedure (or even class) ofthe same file. In most cases, a global variable must be declared inside of a module, that is, between the ModuleModName and the End Module lines but outside of a procedure. Based on this, such a variable is said to have modulescope because it is available to anything inside of that module.

Practical Learning: Declaring Global Constants

1. Change the document as follows:

Module CleaningOrder

Const UnitPriceShirts As Double = 1.25 Const UnitPricePants As Double = 1.95 Const UnitPriceOtherItems As Double = 3.25 Const TaxRate As Double = 5.75

Sub Main()

Dim CustomerName As String, CustomerPhone As String . . . No Change

End Sub

End Module

2. To execute the program, press F5

3. Enter values as follows: Customer Name: Shawn Nitty

Customer Phone: (301) 423-7744

Order Date: 04/11/2008

Order Time 09:12

Number of Shirts: 0

Number of Pants: 2

Number of Other Items: 0

4. Enter the amount tended as 20

5. Close the message box and return to your programming environment

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 77: Microsoft Visual Basic 2010 Tutorial

Modules

Introduction

In the small programs we have created so far, we were using only one file. A typical application uses as many files asnecessary. You can use one file to list some objects used in other files. As we move on, we will see different examplesof creating different files in the same program.

In the Visual Basic language, a file that holds Visual Basic code is called a module.

Creating a Module

As mentioned above, a module is primarily a file that holds code. Therefore, there is no complication with creating one.It is simply a file that holds the .vb extension. If you create a console application using the Console Application optionof the New Project dialog box, Microsoft Visual Studio would create a default file for and would insert the moduletemplate code.

To create a module in Microsoft Visual Studio or Microsoft Visual Basic 2008 Express Edition, on the main menu, youcan click Project -> Add Module... This would display the Add New Item dialog box with the Module selected as defaultin the Templates list. The studio would also suggest a default name. You can accept that name or change it. The nameof the module follows the rules of an object in the Visual Basic language. Once you are ready with the dialog box, youcan click Add.

If you are manually creating your code from Notepad or any text editor, you can simply create any file in your folderand give it the .vb extension.

Probably the most important thing in a module is that the area that contains its code must start with a ModuleModuleName and end with an End Module line:

Module ModuleName

End Module

Anything between these two lines is part of the normal code and everything that is normal code of the module must beinserted between these two lines. No code should be written outside of these two lines.

After creating a module and adding its required two lines, you can add the necessary code. Of course, there are rulesyou must follow. At a minimum, you can declare one or more variables in a module, just as we have done so far. Hereis an example:

Module Exercise Dim FullName As StringEnd Module

Accessing or Opening a Module

Each module of a project is represented in the Solution Explorer by a name under the project node. To open a moduleusing the Solution Explorer:

Right-click the name of the module and click Open

Double-click the module

If there are many opened module, each is represented in the Code Editor by a label and by an entry in the Windowsmenu. Therefore, to access a module:

In the top section of the Code Editor, click its label (or tab)

On the main menu, click Window and click the name of the file

Renaming a Module

As you may have realised, when you start a console application, Microsoft Visual Basic creates a default module andnames it Module1. Of course, you can add as many modules as necessary. At any time, you can change the name of amodule.

To rename a module, in the Solution Explorer

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 78: Microsoft Visual Basic 2010 Tutorial

Right-click the name of the module and click Rename. Type the desired name with the .vb extension and pressEnter

Click the name of the module. In the Properties window, edit the entry in the File Name field

Deleting a Module

If you have a module you don't need anymore, to delete it, in the Solution Explorer, right-click it and click Delete. Youwill receive a warning to confirm your intentions or to change your mind.

Access Modifiers

Introduction

As mentioned already, you can use more than one module in a project and you can declare variables in a module. Thisallows different modules to exchange information. For example, if you are planning to use the same variable in morethan section of your application, you can declare the variable in one module and access that variable in any othermodule in the application.

The Friendly Members of a Module

A variable that is declared in one module and can be accessed from another module in the same application is referredto as a friend. Variables are not the only things that can benefit from this characteristic. We will see other types.

To declare a friendly variable, instead of Dim, you use the Friend keyword. Here is an example:

Module Exercise Friend FullName As StringEnd Module

After declaring such a variable, you can access it from any module of the same application. Here is an example:

File 1: Module1.vb

Module Exercise Friend FullName As StringEnd Module

File 2: Exercise.vb

Module Exercise Sub Main() FullName = "Gertrude Monay" MsgBox("Full Name: " & FullName) End SubEnd Module

The Private Members of a Module

Instead of allowing a member of a module to be accessible outside the module, you may want to restrict this access.The Visual Basic language allows you to declare a variable that can be accessed only within the module that contains it.No code outside the module would be able to "see" such a member. A member inside a module and that is hidden fromother modules is referred to as private.

To declare a private variable, instead of Dim or Friend, you use the Private keyword. Here is an example:

Module Exercise Friend FullName As String Private DateHired As Date

Sub Main() FullName = "Gertrude Monay" DateHired = #4/8/2008# Dim Information As String

Information = "Full Name: " & FullName & vbCrLf & "Date Hired: " & DateHired MsgBox(Information) End Sub

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 79: Microsoft Visual Basic 2010 Tutorial

End Module

This would produce:

Practical Learning: Declaring Global Private Variables

1. Change the document as follows:

Module CleaningOrder

Const UnitPriceShirts As Double = 1.25 Const UnitPricePants As Double = 1.95 Const UnitPriceOtherItems As Double = 3.25 Const TaxRate As Double = 5.75

Private CustomerName As String, CustomerPhone As String Private OrderDate As Date, OrderTime As Date ' Unsigned numbers to represent cleaning items Private NumberOfShirts As UInteger, NumberOfPants As UInteger Private NumberOfOtherItems As UInteger ' Each of these sub totals will be used for cleaning items Private SubTotalShirts As Double, SubTotalPants As Double Private SubTotalOtherItems As Double ' Values used to process an order Private TotalOrder As Double, TaxAmount As Double Private NetTotal As Double Private AmountTended As Double

Sub Main() ' Request order information from the user CustomerName = InputBox("Enter Customer Name:") . . . No Change End Sub

End Module

2. To execute the program, on the Standard toolbar, click the Start Debugging button

3. Enter values as follows: Customer Name: Landry Kurtzmann

Customer Phone: (202) 223-3325

Order Date: 04/12/2008

Order Time 07:35

Number of Shirts: 8

Number of Pants: 2

Number of Other Items: 0

4. Enter the amount tended as 50

5. Close the message box and return to your programming environment

The Public Members of a Module

When working on a project, you may want to create objects or declare variables that you want to be accessible fromother applications. Such a member is referred to as public.

To declare a variable that can be accessed by the same modules of the same project and modules of other projects,declare it using the Public keyword. Here is an example:

Module Exercise Friend FullName As String Private DateHired As Date

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 80: Microsoft Visual Basic 2010 Tutorial

Public HourlySalary As Double

Sub Main() FullName = "Gertrude Monay" DateHired = #4/8/2008# HourlySalary = 36.75 Dim Information As String

Information = "Full Name: " & FullName & vbCrLf & "Date Hired: " & DateHired & vbCrLf & "Hourly Salary: " & HourlySalary MsgBox(Information) End SubEnd Module

This would produce:

Access Modifiers and Modules

The Friend, Private, and Public keywords are called access modifiers because they control the level of access that amember of a module has. In previous sections, we saw how to control the members of a module. The level of access ofa module itself can also be controlled. To control the level of access of a module, you can precede the Module keywordwith the desired access modifier.

The access modifier of a module can only be either Friend or Public. Here are examples:

File 1: Module1.vb

Friend Module Exercise End Module

File 2: Module2.vb

Public Module Exercise End Module

If a module is set to Friend, its Public and Friend members can be accessed by other members of modules of thesame application. The public members cannot be accessed outside of the same application. This means that if youcreate an application A that has a friend module M and that module contains a public variable V, that variable Vcannot be accessed by a module N from another application B

If a module is set Public:

Its Friend members can be accessed by friend and public modules of the same application. The friendmembers cannot be accessed outside of its application (even if the module is Public)

Its Public members can be accessed by modules inside the same application and modules in otherapplications (outside its application)

Practical Learning: Access Modifying a Module

1. Change the document as follows:

Public Module CleaningOrder

. . . No Change

End Module

2. On the Standard toolbar, click the Start button

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 81: Microsoft Visual Basic 2010 Tutorial

3. Enter values as follows: Customer Name: William Nessif

Customer Phone: (301) 220-3737

Order Date: 04/12/2008

Order Time 08:26

Number of Shirts: 3

Number of Pants: 3

Number of Other Items: 3

4. Enter the amount tended as 40

5. Close the message box and return to your programming environment

Details on Declaring Variables

Declaring a Series of Variables

Because a program can use different variables, you can declare each variable on its own line.Here are examples:

Module Exercise Sub Main() Dim NumberOfPages As Integer Dim TownName As String Dim MagazinePrice As Double End SubEnd Module

It is important to know that different variables can be declared with the same data type as inthe following example:

Module Exercise Sub Main() Dim NumberOfPages As Integer Dim Category As Integer Dim MagazinePrice As Double End SubEnd Module

When two variables use the same data type, instead of declaring each on its own line, you candeclare two or more of these variables on the same line. There are two techniques you can use:

You can write the names of both variables on the same line, separated by a comma, andending the line with the common data type:

Module Exercise Sub Main() Dim NumberOfPages, Category As Integer Dim MagazinePrice As Double End SubEnd Module

In this case, both variables NumberOfPages and Category, are the same type, Integer

You can also declare, on the same line, variables that use different data types. To do this,type the Dim keyword followed by the variable name and its data type with the Askeyword. Then type a comma, followed by the other variable(s) and data type(s). Here is anexample

Module Exercise Sub Main() Dim NumberOfPages, Category As Integer Dim CountryName As String, MagazinePrice As Double End SubEnd Module

In this case, CountryName is a string variable while MagazinePrice is a Double variable

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 82: Microsoft Visual Basic 2010 Tutorial

You can use the same techniques when declaring many global variables. Here are examples:

Module Exercise Friend FirstName As String, LastName As String Private DateHired As Date, HourlySalary As Double

Sub Main() End Sub

End Module

After declaring the variables, you can initialize and use them as you see fit.

Read-Only Variables

We have indicated that when a variable is declared, it receives a default initialization unless youdecide to specify its value. Whether such a variable has been initialized or not, at any time, youcan change its value by reassigning it a new one. Here is an example:

Module Exercise

Sub Main() ' Initializing a variable when declaring it Dim Number As Double = 155.82 MsgBox("Number: " & Number)

' Changing the value of a variable after using it Number = 46008.39 MsgBox("Number: " & Number) End Sub

End Module

This would produce:

In the same way, we saw that you could declare a variable at module scope outside of Mainand then initialize or change its value when necessary. Here is an example:

Module Exercise

Private UnitPrice As Double Private DateOfBirth As Date = #12/5/1974# Private Number As Double

Sub Main() ' Initializing a variable Number = 155.82 MsgBox("Number: " & Number)

' Changing the value of a variable after using it Number = 46008.39 MsgBox("Number: " & Number) End Sub

End Module

When declaring a variable, as the programmer, you should have an idea of how you want to usethe variable and what type of values the variable should hold. In some cases, you may want thevariable to hold a constant value and not be able to change it. We saw earlier that such avariable could be declared as a constant. An alternative is to declare it with the ReadOnlykeyword. While a constant variable can be declared locally, a ReadOnly variable cannot. It mustbe declared globally.

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 83: Microsoft Visual Basic 2010 Tutorial

As done for a constant, when declaring a ReadOnly variable, you should initialize it. If you donot, the compiler would assign the default value based on its type. For example, a number-based variable would be initialized with 0 and a String variable would be initialized with anempty string. As done so far, to initialize the variable, use the assignment operator followed bythe desired value.

Like a constant, after declaring and optionally initializing a ReadOnly variable, you cannotchange its value. Based on this, the following code would produce an error:

Module Exercise

Dim UnitPrice As Double Dim DateOfBirth As Date = #12/5/1974# ReadOnly Number As Double = 155.82

Sub Main() ' Initializing a variable Number = 155.82 MsgBox("Number: " & Number)

' Changing the value of a variable after using it Number = 46008.39 ' Error: You cannot assign a value to ' a ReadOnly variable after initializing it MsgBox("Number: " & Number) End Sub

End Module

In the Microsoft Visual Basic 2010, the parser would signal the errors by underlining the read-only variable when you try changing its value. A window named Error List would also point outthe problems:

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 84: Microsoft Visual Basic 2010 Tutorial

This means that a ReadOnly variable must be assigned a value once, when initializing it.

Managing Variables

Accessing a Variable

As mentioned already, you will write your code in normal text editors, whether using Notepad,the Code Editor of Microsoft Visual Studio, or else. Also, you may be familiar already with howto look for a character, a symbol, a word, or a group of words in a document. Just as reminder,on the main menu of the application, you can click Edit -> Find... This would display a dialogbox where you can type the item and click Find. If you are using Microsoft Visual Studio and ifyou want to find different occurrences of a known character, symbol, word, or group of words,first select that item. Then:

On the main menu, click Edit -> Quick Find

Press Ctrl + F

In the same way, if you have a variable that is used more than once in your code and you wantto see all places where that variable is used, simply click the name (and wait two seconds) andall of its occurrences would be highlighted:

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 85: Microsoft Visual Basic 2010 Tutorial

To get a list of all sections where the variable is used, if you are using Microsoft Visual Studio:

In the Code Editor, right-click the name of the variable and click Find All References

Press Ctrl + F12

This would produce a list of all sections where the variable is used and would display the list inthe Find Symbol Results window:

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 86: Microsoft Visual Basic 2010 Tutorial

To access a particular section where the variable is used, double-click its entry in the list int theFind Symbol Results window.

Cutting, Copying, and Pasting Code

Normally, from your knowledge of using computers, you probably already know how to select,cut, and copy text. These two operations can be valuable to save code in Microsoft VisualStudio. This means that, if you have code you want to use in different sections, you canpreserve it somewhere to access it whenever necessary.

To save code to use over and over again, first type the code in any text editor, whether inNotepad, Microsoft Word, or the Code Editor of Microsoft Visual Studio. You can use code fromany document where text can be copied, including a web page. Select that code and copy it tothe clipboard. To preserve it, in Microsoft Visual Studio, display the Toolbox (on the main menu,you can click View -> Toolbox). Right-click an empty area on the Toolbox and click Paste:

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 87: Microsoft Visual Basic 2010 Tutorial

An alternative is to select the code, whether in the Code Editor or in a text editor. Then drag itand drop it on the Toolbox. In the same way, you can add different code items to the Toolbox.After pasting or adding the code to the Toolbox, it becomes available. To use that code, drag itfrom the Toolbox and drop it in the section of the Code Editor where you want to use it.

Renaming a Variable

As we will see throughout our lessons, there are many names you will use in your programs.After creating a name, in some cases you will have to change it. You can find where the nameis and edit it. If the name is used in many places, you can continue looking for it and modify it.There is a chance you will make a mistake. If you are writing your code using a text editor, youcan use the Edit -> Replace option of the main menu to find and replace every instance of thatname. You can use the same approach in the Code Editor. Unfortunately, this technique worksfor only one file. If your project has many files and the name is used in those files, it would becumbersome to remember to change the name in all of them.

Microsoft Visual Studio makes it easy to find and change a name wherever it is used. Considerthe following code:

Module Exercise Public Sub Main() Dim nbr As Integer

nbr = 148

System.Console.WriteLine(nbr) End SubEnd Module

To change the name of a variable, in the Code Editor, double-click the name of the variable andedit (change) it. The name will then have a small underline:

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 88: Microsoft Visual Basic 2010 Tutorial

If you position your mouse on it, a tag would appear and you can click the arrow to reveal ashort menu:

If you click the Rename option, all instances of the variable would be changed.

Accessing a Variable's Declaration

If you create a long document that has many lines of code, in a certain section you mayencounter a variable but you want to find out where it was declared. If you are using MicrosoftVisual Studio, to access the place where a variable was declared:

Right-click the variable and click Go To Definition...

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 89: Microsoft Visual Basic 2010 Tutorial

Click the name of the variable and press Shift + F2

In both cases, the caret would jump to where the variable was declared.

Accessing a Line of Code by its Index

If you are using the Code Editor of Microsoft Visual Studio, if you create a long document thathas many lines of code, if you want to jump to a certain line of code:

On the main menu, click Edit -> Go To...

Press Ctrl + G

This would display a dialog box. Enter the line number and click OK or press Enter.

Application: Ending the Lesson

1. On the main menu, click File -> Close Solution (Microsoft Visual Studio) or File -> CloseProject (Microsoft Visual Basic 2010 Express)

2. When asked whether you want to save, click Discard

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 90: Microsoft Visual Basic 2010 Tutorial

Previous Copyright © 2008-2010 FunctionX Home

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 91: Microsoft Visual Basic 2010 Tutorial

Enumerations

Introduction

Imagine you are creating a program for a real estate company (a business that sells houses).You want the program to ask a customer the type of house she wants to purchase and/or thetype of garage that the desired house should have. Here is an example:

Module Exercise

Public Function Main() As Integer Dim TypeOfHouse As Integer Dim TypeOfGarage As Integer

TypeOfHouse = InputBox("Enter the type of house you want to purchase" & vbCrLf & "1 - Single Family" & vbCrLf & "2 - Townhouse" & vbCrLf & "3 - Condominium" & vbCrLf & "Your Choice: ") TypeOfGarage = InputBox("Enter the type of garage you want" & vbCrLf & "0 - Doesn't matter" & vbCrLf & "1 - Interior" & vbCrLf & "2 - Exterior" & vbCrLf & "Your Choice: ")

MsgBox("House Type: " & TypeOfHouse & vbCrLf & "Garage Type: " & TypeOfGarage) Return 0 End Function

End Module

Here is an example of running the program:

For such a program, the numbers can be vague. 1 can be considered a general number but, in ourprogram, it can represent a Single Family house or an Interior type of garage. At the same time,

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 92: Microsoft Visual Basic 2010 Tutorial

our program uses the constant 1 in particular meaningful ways. To make it possible to give moremeaning to a constant number, when the number can be made part of a series, you can/shouldcreate a type of list.

An enumeration is a series of constant integers that each has a specific position in the list and canbe recognized by a meaningful name. Based on this, instead of just remembering that the constant1 represents Single Family, you can create a list that has that type of house. In another list,instead of using 1 again, you can give it a name. Consequently, in each list, although the constant1 would still be considered, at least it would mean something precise.

Creating an Enumeration

Tou can create an enumeration manually or let Microsoft Visual Basic create a skeleton code foryou. To manually write the code, on a first line of code, type the Enum keyword followed by aname. On another line, end the enumeration with End Enum. Here is an example:

Enum HouseTypes

End Enum

If you are using Microsoft Visual Studio and you it to generate an enumeration code for you, right-click the section where you want to add it and click Insert Snippet... In the menu, double-clickCode Patterns, If, For Each, Property, etc... Double-click Enum, Generics, Interfaces, Structures.Double-click Define an Enumeration:

The section between the Enum Name and the End Enum lines is the body of the enumeration. Inthat body, add the members of the enumeration, each on its own line. Here is an example:

Enum HouseType Unknown SingleFamily TownHouse CondominiumEnd Enum

A Variable of an Enumeration Type

After creating an enumeration, it becomes a type and can be used like a data type. For example,you can declare a variable of its type. You use the same formula of any variable. Here is anexample:

Module Exercise Enum HouseType Unknown SingleFamily TownHouse Condominium End Enum

Public Function Main() As Integer Dim ht As HouseType

Return 0 End Function

End Module

After declaring the variable, you can use it as you see fit. Here is an example:

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 93: Microsoft Visual Basic 2010 Tutorial

Module Exercise Enum HouseType Unknown SingleFamily TownHouse Condominium End Enum

Public Function Main() As Integer Dim ht As HouseType

MsgBox(ht)

Return 0 End Function

End Module

To initialize a variable of an enumeration type, you must specify which member of the enumerationwould be assigned to the variable. You should only assign a known member of the enumeration.To do this, on the right side of the assignment operator, type the name of the enumeration,followed by the period operator, and followed by the member whose value you want to assign.Here is an example:

Module Exercise Enum HouseType Unknown SingleFamily TownHouse Condominium End Enum

Public Function Main() As Integer Dim ht As HouseType

ht = HouseType.SingleFamily

MsgBox(ht)

Return 0 End Function

End Module

The Values of Members of an Enumeration

Each member of an enumeration holds a value of a natural number, such as 0, 1, 2, 3, etc. Thenumber 0 is given, to the first member. The number 1 is given to the second member, and so on.If you don't like those values, you can change them.

Suppose you want the first member to hold a value other than 0. To specify the value of amember, assign to the member using the assignment operator "=". Here is an example:

Enum HouseType Unknown = 5 SingleFamily TownHouse CondominiumEnd Enum

After doing this, the member that follows it would receive a value + 1. In our example, Unknownnow would have a value of 5, SingleFamily would have a value of 6 because it follows a memberwhose value is 1 (thus 5 + 1 = 6). Townhouse would have a value of 7, and Condominium wouldhave a value of 8.

You can also assign a value to more than one member of an enumeration. To do this, simplyassign the desired value to any member. Here are examples:

Enum HouseType Unknown = 5 SingleFamily = 14 TownHouse Condominium = 8End Enum

In this case, Townhouse would have a value of 15 because it follows SingleFamily that has a valueof 14.

Enumerations Visibility

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 94: Microsoft Visual Basic 2010 Tutorial

You can control an enumeration's accessibility outside of its project. This means that you can hideor make it visible outside of its project. To do this, you can precede it with the Private, theProtected, the Friend, or the Public keyword. Here is an example:

Module Exercise Public Enum HouseType Unknown = 5 SingleFamily = 14 TownHouse Condominium = 8 End Enum

Public Function Main() As Integer Dim ht As HouseType

ht = HouseType.SingleFamily

Return 0 End Function

End Module

Passing an Enumeration as Argument

As mentioned already, once an enumeration has been created, it becomes a type. It can be passedas argument and it can be returned from a function.

You pass an enumeration as argument using the same approach of a normal data type. Here is anexample:

Private Sub ShowHouse(ByVal PropType As HouseType)

End Sub

In the same way, you can pass as many enumeration types as necessary. In the body of theprocedure, you can use the enumeration as you see fit. When calling the procedure, pass anargument that holds a value of the type of enumeration. Here is an example:

Module Exercise Public Enum HouseType Unknown = 2 SingleFamily = 4 TownHouse = 6 Condominium = 8 End Enum

Private Sub ShowHouse(ByVal PropType As HouseType) MsgBox("Type of house: " & PropType) End Sub

Public Function Main() As Integer Dim ht As HouseType

ht = HouseType.SingleFamily ShowHouse(ht)

Return 0 End Function

End Module

This would produce:

You can also pass the argument as optional. When creating the procedure, use the Optionalkeyword to specify that the argument has a default value. When calling the procedure, you canpass or omit passing a value for the argument. Here is an example:

Module Exercise Public Enum HouseType Unknown SingleFamily

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 95: Microsoft Visual Basic 2010 Tutorial

TownHouse Condominium End Enum

Private Sub ShowHouse(Optional ByVal PropType As HouseType = HouseType.Unknown) MsgBox("Type of house: " & PropType) End Sub

Public Function Main() As Integer Dim ht As HouseType

ht = HouseType.SingleFamily ShowHouse()

Return 0 End Function

End Module

This would produce:

Returning an Enumeration From a Function

To create a function that returns an enumeration, specify its As factor with the name of theenumeration. In the body of the enumeration, do whatever you have to do. Before exiting thefunction, make sure you return a value that is the type of the enumeration. Here is an example:

Private Function SpecifyPropertyType() As HouseType Dim pt As HouseType

pt = HouseType.TownHouse Return ptEnd Function

You can call a function that returns an enumeration type by using just its name. Otherwise, youcan use its returned value. Here is an example:

Module Exercise Public Enum HouseType Unknown SingleFamily TownHouse Condominium End Enum

Private Sub ShowHouse(Optional ByVal PropType As HouseType = HouseType.Unknown) MsgBox("Type of house: " & PropType) End Sub

Private Function SpecifyPropertyType() As HouseType Dim pt As HouseType

pt = HouseType.TownHouse Return pt End Function

Public Function Main() As Integer Dim ht As HouseType

ht = SpecifyPropertyType() ShowHouse(ht)

Return 0 End Function

End Module

This would produce:

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 96: Microsoft Visual Basic 2010 Tutorial

Home Copyright © 2010 FunctionX, Inc.

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 97: Microsoft Visual Basic 2010 Tutorial

Strings

Introduction to Strings

Overview

As seen in Lesson 3, a string is one or a combination of characters. To declare a variable forit, you can use either the String or the Object data types. To initialize the variable, put itsvalue in double-quotes and assign it to the variable. Here are examples:

Public Module Exercise

Public Function Main() As Integer Dim FirstName As Object Dim LastName As String

FirstName = "William" LastName = "Sansen"

Return 0 End Function

End Module

Producing a Beeping Sound

If you want, you can make the computer produce a beeping a sound in response to something,anything. To support this, the Visual Basic language provides a function called Beep. Its syntaxis:

Public Sub Beep()

Here is an example of calling it:

Module Exercise

Public Function Main() As Integer Beep() Return 0 End Function

End Module

If this function is called when a program is running, the computer emits a brief sound.

String Concatenation

As seen in Lesson 2, string concatenation consists of adding one string to another. to supportthis operation, you can use either the + or the & operator. Here are examples:

Public Module Exercise

Public Function Main() As Integer Dim FirstName As Object Dim LastName As String Dim FullName As String

FirstName = "William" LastName = "Sansen" FullName = LastName + ", " & FirstName

MsgBox("Full Name: " & FullName) Return 0 End Function

End Module

This would produce:

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 98: Microsoft Visual Basic 2010 Tutorial

If you have many strings to add to a primary string, you can use either the += or the &=operator. Here is an example:

Public Module Exercise

Public Function Main() As Integer Dim FullName As String

FullName = "Sansen" FullName += ", " FullName += "William"

MsgBox("Full Name: " & FullName) Return 0 End Function

End Module

Introduction to Characters

Character Duplication

In Lesson 3, we had a brief introduction to strings. We learned that a string was a combinationof characters.

From our knowledge of using the computer, we know that, to create a string, we can press thedesired characters on the keyboard. An example of a string would be: "Production". To have arepeating character in a string, you can press its key as many times as you want. For example,in "cooperation", you would press o twice. To programmatically perform such an operation, thatis, to duplicate a character in a string, you can call the StrDup() function. This function isprovided in two versions whose syntaxes are:

Public Shared Function StrDup( _ ByVal Number As Integer, _ ByVal Character As { Char | String } _) As String' -or-Public Shared Function StrDup( _ ByVal Number As Integer, _ ByVal Character As Object _) As Object

The second argument is the character that will be duplicated. The first argument specifies thenumber of times to duplicate it. Here is an example:

Public Function Main() As Integer Dim Start As Char = "We need your c" Dim End$ = "peration to expedite this matter" Dim Result$

Result$ = Start & StrDup(2, "o") & End$

MsgBox(Result$) Return 0End Function

This would produce:

Expression Character Conversion

If you have such a string, you may be interested in the individual characters it contains. InLesson 3, we also saw that, to convert an expression to a character, you can call the CChar()

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 99: Microsoft Visual Basic 2010 Tutorial

function. Its syntax is:

Function CChar(ByVal Expression As Object) As Char

This function takes a value as argument. The argument must be convertible to a character. Ifso, the function returns a character.

Getting the ASCII Character of a Number

The characters used in the US English and the most common characters of Latin-basedlanguages are created in a list or map of character codes. Each character is represented with asmall number between 0 and 255. This means that each character must fit in a byte.

To help you find the equivalent ASCII character of such a number, the Visual Basic languageprovides a function named Chr. Its syntax is:

Public Function Chr(ByVal CharCode As Integer) As Char

When calling this function, pass a small number as argument. Here is an example:

Public Module Exercise

Public Function Main() As Integer Dim Character As Char Dim Number As Integer

Number = 114 Character = Chr(Number)

MsgBox("The ASCII character of " & Number & " is " & Character) Return 0 End Function

End Module

This would produce:

Besides finding the ASCII equivalent of a number, the Chr() function can be used to applysome behavior in a program. For example, a combination of Chr(13) and Chr(10) would breaka line in an expression, which is equivalent to the vbCrLf operator.

Getting the Wide ASCII Character of a Number

If you pass a number lower than 0 or higher than 255 to the Chr() function, you would receivean error. The reason you may pass a number higher than 255 is that you may want to get acharacter beyond those of US English, such as â. To support such numbers, the Visual Basiclanguage provides another version of the function. Its syntax is:

Public Function ChrW(ByVal CharCode As Integer) As Char

The W here represents Wide Character. This makes it possible to store the character in thememory equivalent to the Short integer data type, which can hold numbers from -32768 to32767. Normally, you should consider that the character should fit in a Char data type,, whichshould be a positive number between 0 and 65535.

Here is an example:

Public Module Exercise

Public Function Main() As Integer Dim Character As Char Dim Number As Short

Number = 358 Character = ChrW(Number)

MsgBox("The ASCII character of " & Number & " is " & Character) Return 0 End Function

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 100: Microsoft Visual Basic 2010 Tutorial

End Module

This would produce:

The Length of a String

One of the most fundamental characteristics of a string is the number of characters it contains.This number is referred to as the length of a string. To assist you with finding the length of astring, the Visual Basic language provides a function named Len. Its syntax is:

Public Shared Function Len(ByVal Expression As String) As Integer

This function expects a string as argument. If the function succeeds in counting the number ofcharacters, which it usually does, it returns the an integer. Here is an example:

Public Module Exercise

Public Function Main() As Integer Dim Item As String Dim Length As Integer

Item = "Television" Length = Len(Item)

MsgBox("The number of characters in """ & Item & """ is " & Length) Return 0 End Function

End Module

This would produce:

Characters, Strings, and Procedures

Passing a Character or a String to a Procedure

Like a normal value, a character or a string can be passed to a procedure. When creating theprocedure, enter the argument and its name in the parentheses of the procedure. Then, in thebody of the procedure, use the argument as you see fit. Here is an example:

Public Module Exercise

Private Sub Show(ByVal Gdr As Char) MsgBox(Gdr) End Sub

End Module

When calling the procedure, you can pass a value for the argument in double-quotes. Here isan example:

Public Module Exercise

Private Sub Show(ByVal Sex As Char) MsgBox(Sex) End Sub

Public Function Main() As Integer Show("F") Return 0 End Function

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 101: Microsoft Visual Basic 2010 Tutorial

End Module

In the same way, you can apply any of the features we studied for procedures, includingpassing as many arguments as you want or passing a mixture of characters, strings, and othertypes of arguments. You can also create a procedure that receives an optional argument.

Returning a Character or a String From a Function

To create a function that returns a character or a string, create the procedure using theFunction keyword and, on the right side of the parentheses, include the Char or String datatype preceded by the As keyword. Here is an example we saw in Lesson 5:

Public Module Exercise

Function GetFullName$() Dim FirstName$, LastName$

FirstName = InputBox("Enter First Name: ") LastName = InputBox("Enter Last Name: ")

Return LastName & ", " & FirstName End Function

End Module

When calling the function, you can use it as a normal procedure or you can retrieve the value itreturns and use it as you see fit. Here is an example:

Public Module Exercise

Function GetFullName$() Dim FirstName$, LastName$

FirstName = InputBox("Enter First Name: ") LastName = InputBox("Enter Last Name: ")

GetFullName = LastName & ", " & FirstName End Function

Private Sub Show(ByVal Name As String, ByVal Gdr As String) MsgBox("=-= Student Registration =-=" & vbCrLf & _ "Full Name: " & Name & vbCrLf & _ "Gender: " & vbTab & Gdr) End Sub

Public Function Main() As Integer Dim FullName As String

FullName = GetFullName() Show(FullName, "Unknown") Return 0 End Function

End Module

Here is an example of executing the program:

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 102: Microsoft Visual Basic 2010 Tutorial

In the same way, you can apply any of the features of procedures and functions we studied inLessons 5 and 6.

The Characters of a String

Getting the Character From its Position in a String

As mentioned already, a string is a combination of symbols or characters. An example is"Television". Each character in a string has an indexed position from 1 to its last character:

T e l e v i s i o n

1 2 3 4 5 6 7 8 9 10

To find out what character occupies a certain position inside of a string, you can call theGetChar() function. Its syntax is:

Public Shared Function GetChar( _ ByVal str As String, _ ByVal Index As Integer _) As Char

The first argument is the string that will be considered. If you pass this argument as an emptystring or Nothing, you would receive an error.

The second argument is the position to be consider inside the string. The value must bebetween 1 and the length of the string. Here is an example:

Public Module Exercise

Public Function Main() As Integer Dim Item As String

Item = "Television"

MsgBox("The character at position 5 is " & GetChar(Item, 5)) Return 0 End Function

End Module

This would produce:

Getting the ASCII Numeric Equivalent of a Character

If you have a character and want to find its equivalent character, you can call the Asc()function. Its syntax is:

Public Overloads Function Asc(ByVal String As Char) As Integer

This function takes a character as argument. If the function is successful, it returns the numericequivalent. Here is an example:

Public Module Exercise

Public Function Main() As Integer Dim Character As Char Dim Number As Integer

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 103: Microsoft Visual Basic 2010 Tutorial

Character = "W" Number = Asc(Character)

MsgBox("The number of " & Character & " is " & Number) Return 0 End Function

End Module

This would produce:

Character and String Conversions

Introduction

In Lesson 3, we saw that, to convert an expression to a string, you can call the CStr()function. Its syntax is:

Public Function CStr(ByVal Expression As Object) As String

The argument can be almost any expression but the compiler has to be able to convert it to astring, which in most cases it can. If it is successful, the function returns a string. Here is anexample:

Public Module Exercise

Public Function Main() As Integer Dim DateHired As Date

DateHired = #1/4/2005#

MsgBox("Date Hired: " & CStr(DateHired)) Return 0 End Function

End Module

This would produce:

The CStr() function is used to convert any type of value to a string. If the value to beconverted is a number, you can use the Str() function. Its syntax is:

Public Shared Function Str(ByVal Number As Object) As String

This function expects a number as argument. Here is an example:

Public Module Exercise

Public Function Main() As Integer Dim Number As Double

Number = 1450.5 / 2

MsgBox("1450.50 / 2 = " & Str(Number)) Return 0 End Function

End Module

This would produce:

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 104: Microsoft Visual Basic 2010 Tutorial

Numeric Hexadecimal Conversion

In Lesson 3, we saw that the Visual Basic language supports hexadecimal number and we sawhow to initialize an integer variable with a hexadecimal number. Now, on the other hand, if youhave a decimal number but need it in hexadecimal format, you can convert it. To support thisoperation, you can call the Hex() function. Its syntax is:

Public Shared Function Hex( _ ByVal Number As { Byte | SByte | Short | UShort | Integer | UInteger | Long | ULong | Object } _) As String

This function is used to convert either an integer-based or a decimal number to its hexadecimalequivalent. It returns the result as a string. Here is an example:

Public Module Exercise

Public Function Main() As Integer Dim Number As UInteger

Number = 286345 MsgBox(CStr(Number) & " in hexadecimal format is " & Hex(Number))

Return 0 End Function

End Module

This would produce:

Numeric Octal Conversion

If you have a decimal number you want to convert to its octal format, you can call the Oct()function. Its syntax is:

Public Shared Function Oct( _ ByVal Number As { Byte | SByte | Short | UShort | _ Integer | UInteger | Long | ULong | Object } _) As String

This function takes an integer-based or a decimal number and converts its octal equivalent. Itreturns the result as a string. Here is an example:

Public Module Exercise

Public Function Main() As Integer Dim Number As Integer

Number = 286345 MsgBox(CStr(Number) & " in octal format is " & Oct(Number))

Return 0 End Function

End Module

This would produce:

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 105: Microsoft Visual Basic 2010 Tutorial

Case Conversion

If you are presented with a string or an expression whose cases must be the same, you canconvert all of its characters in either uppercase or lowercase.

To convert a character, a string or an expression to uppercase, you can call the UCase()function. These functions take one argument as the string or expression to be considered. Thesyntaxes are:

Public Shared Function UCase(ByVal Value As Char) As CharPublic Shared Function UCase(ByVal Value As String) As String

The first version receives a character as argument. If the character is already in uppercase, itwould be returned the same. If the character is not a readable character, no conversion wouldhappen and the function would return it. If the character is in lowercase, it would be convertedto uppercase and the function would then return the uppercase equivalent.

The second version considers the argument supplied as a string. Any letter that is in lowercasein the string would be converted to uppercase. Any letter that is in uppercase would bepreserved and would not be changed. Any non-alphabetic character in the string would be kept"as is".

Here is an example:

Public Module Exercise

Public Function Main() As Integer Dim ProgrammingEnvironment As String

ProgrammingEnvironment = "Microsoft Visual Basic 2008 Express Edition"

MsgBox(UCase(ProgrammingEnvironment)) Return 0 End Function

End Module

This would produce:

To convert a character or a string to lowercase, you can call the LCase() function. It isoverloaded in two versions whose syntaxes are:

Public Shared Function LCase(ByVal Value As Char) As CharPublic Shared Function LCase(ByVal Value As String) As String

The first version receives a character as argument. If the character is not a readable symbol, itwould be kept "as is". If the character is in lowercase, it would not be converted. If thecharacter is in uppercase, it would be converted to lowercase.

The second version of the function receives a string as argument. Any letter in uppercase in thestring would be converted to lowercase. Any letter that is in lowercase would not be changed.Any non-alphabetic character in the string would be kept "as is".

Besides the UCase() and the LCase() functions, to convert the cases of characters in a string,the Visual Basic language provides the StrConv() function. Its syntax is:

Public Shared Function StrConv( _ ByVal str As String, _ ByVal Conversion As Microsoft.VisualBasic.VbStrConv, _ Optional ByVal LocaleID As Integer, ) As String

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 106: Microsoft Visual Basic 2010 Tutorial

This function produces a string. The first argument of this function is the string whosecharacters would be converted. The second argument specifies what type of conversion will beperformed. This argument is a member of the VbStrConv enumeration. From what we havelearned so far, this argument can have one of the following values:

VbStrConv.None: There will be no conversion

VbStrConv.UpperCase: This would have the same effect as the UCase$ function. Itconverts the first argument's characters to uppercase. Here is an example:

Public Function Main() As Integer Dim ProgrammingEnvironment As String Dim Result$

ProgrammingEnvironment = "Microsoft Visual Basic 2008 Express Edition" Result$ = StrConv$(ProgrammingEnvironment, VbStrConv.Uppercase)

MsgBox(Result$) Return 0End Function

VbStrConv.LowerCase: This would have the same effect as the LCase$ function. Itconverts the first argument's characters to lowercase

VbStrConv.ProperCase: The first character of each word of the first argument would beconverted to uppercase. Here is an example:

Public Function Main() As Integer Dim MCQ$ Dim Result$

MCQ$ = "multiple choice question examination" Result$ = StrConv$(MCQ$, VbStrConv.ProperCase)

MsgBox(Result$) Return 0End Function

This would produce:

The last argument is optional. It allows you to specify that language whose rules would be usedto direct the conversion. By default, the compiler refers to the language of the operationsystem. In most computers in the United States, this would be US English. If for some reason,you would like to apply different rules, specify its language as the third argument.

The Sub-Strings of a String

Introduction

A sub-string is a character or a group of characters or symbols that are part of an existing string.The Visual Basic language provides functions to create, manipulate or manage sub-strings. Theprimary rule to keep in mind is that a sub-string is part of, and depends on, a string. In otherwords, you cannot have a sub-string if you do not have a string in the first place.

The Left Sub-String of a String

If you have an existing string but want to create a new string using a number of characters fromthe left side characters of the string, you can use the Left() function. Its syntax is:

Public Shared Function Left( ByVal str As String, ByVal Length As Integer) As String

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 107: Microsoft Visual Basic 2010 Tutorial

The function takes two arguments and both are required. The first argument is the existing string.The second argument is the number of characters counted from the left side of the string. Here isan example:

Public Module Exercise

Public Function Main() As Integer Dim Process As String

Process = "learning"

MsgBox("To " & Left(Process, 5) & " is to gain understanding") Return 0 End Function

End Module

This would produce:

The Right Sub-String of a String

To create a new string using one or more characters from the right side of an existing string, call afunction named Right. Its syntax is:

Public Shared Function Right(ByVal str As String, ByVal Length As Integer) As String

Both arguments are required. The first argument is the original string. The second argument is thenumber of characters counted from the right side of the string. Here is an example:

Public Module Exercise

Public Function Main() As Integer Dim ProgrammingEnvironment As String

ProgrammingEnvironment = "Microsoft Visual Basic"

MsgBox("Q" & Right(ProgrammingEnvironment, 5) & " in MS DOS 5.2") Return 0 End Function

End Module

This would produce:

The Mid Sub-String of a String

You may want to create a string using some characters either from the left, from the right, orfrom somewhere inside an existing string. To assist you with this, the Visual Basic languageprovides a function named Mid. Its syntax is:

Public Module Exercise

Public Function Main() As Integer Dim ProgrammingEnvironment As String

ProgrammingEnvironment = "Microsoft Visual Basic 2008 Express Edition"

MsgBox("The " & Mid(ProgrammingEnvironment, 10, 13) & " language") Return 0 End Function

End Module

This would produce:

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 108: Microsoft Visual Basic 2010 Tutorial

Finding a Sub-String

One of the most regular operations you will perform on a string consists of finding out whether itcontains a certain character or a certain contiguous group of characters. To help you with thisoperation, the Visual Basic language provides the InStr() function. It is overloaded with twoversions whose syntaxes are:

Public Shared Function InStr(_ ByVal String1 As String, _ ByVal String2 As String, _ Optional ByVal Compare As CompareMethod _) As Integer' -or-Public Shared Function InStr(_ ByVal Start As Integer, _ ByVal String1 As String, _ ByVal String2 As String, _ Optional ByVal Compare As Microsoft.VisualBasic.CompareMethod _) As Integer

In the first version of the function, the String1 argument is the string on which the operation willbe performed. The String2 argument is the character or the sub-string to look for. If String2 isfound in String1 (as part of String1), the function return the position of the first character. Here isan example:

Public Module Exercise

Public Function Main() As Integer Dim ProgrammingEnvironment As String

ProgrammingEnvironment = "Microsoft Visual Basic Express Edition"

MsgBox("In " & ProgrammingEnvironment & ", ""Basic"" is found at position " & _ InStr(ProgrammingEnvironment, "Basic")) Return 0 End Function

End Module

This would produce:

The first version of the function asks the interpreter to check String1 from the left looking forString2. If String1 contains more than one instance of String2, the function returns (only) theposition of the first instance. Any other subsequent instance would be ignored. If you want to skipthe first instance or want the interpreter to start checking from a position other than the leftcharacter, use the second version. In this case, the Start argument allows you to specify thestarting position from where to start looking for String2 in String1.

The InStr() function is used to start checking a string from the left side. If you want to startchecking from the right side, call the InStrRev() function. Its syntax is:

Public Function InStrRev( ByVal StringCheck As String, ByVal StringMatch As String, Optional ByVal Start As Integer = -1, Optional ByVal Compare As CompareMethod = CompareMethod.Binary) As Integer

Replacing a Character or a Sub-String in a String

After finding a character or a sub-string inside of a string, you can take action on it. One of theoperations you can perform consists of replacing that character or that sub-string with another

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 109: Microsoft Visual Basic 2010 Tutorial

character or a sub-string. To do this, the Visual Basic language provides the Replace() function.Its syntax is:

Public Function Replace( ByVal Expression As String, ByVal Find As String, ByVal Replacement As String, Optional ByVal Start As Integer = 1, Optional ByVal Count As Integer = -1, Optional ByVal Compare As CompareMethod = CompareMethod.Binary) As String

The first argument is the string on which the operation will be performed. The second argument isthe character or string to look for in the Expression. If that character or string is found, the thirdargument is the character or string to replace it with. Here is an example:

Public Module Exercise

Public Function Main() As Integer Dim ProgrammingEnvironment As String

ProgrammingEnvironment = "Microsoft Visual Basic 2008 Express Edition"

MsgBox(Replace(ProgrammingEnvironment, "Basic", "C++")) Return 0 End Function

End Module

This would produce:

Other Operations on Strings

Reversing a String

Once a string has been initialized, one of the operations you can perform on it consists of reversingit. To do this, you can call the StrReverse() function. Its syntax is:

Public Function StrReverse(ByVal Expression As String) As String

This function takes as argument the string that needs to be reversed. After performing itsoperation, the function returns a new string made of characters in reverse order. Here is anexample:

Public Function Main() As Integer Dim StrValue As String Dim StrRev As String

StrValue = "République d'Afrique du Sud" StrRev = StrReverse(strValue)

MsgBox(StrValue & vbCrLf & StrRev) Return 0End Function

This would produce:

Because the StrReverse() function returns a string, you can write it as StrReverse$.

Strings and Empty Spaces

The simplest string is probably one that you declared and initialized. In some other cases, you may

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 110: Microsoft Visual Basic 2010 Tutorial

work with a string that you must first examine. For example, for some reason, a string maycontain an empty space to its left or to its right. If you simply start performing a certain operationon it, the operation may fail. One of the first actions you can take on a string would consist ofdeleting the empty space(s), if any on its sides.

To remove all empty spaces from the left side of a string, you can call the LTrim() function. Itssyntax is:

Public Shared Function LTrim(ByVal str As String) As String

To remove all empty spaces from the right side of a string, you can call the RTrim() function. Itssyntax is:

Public Shared Function RTrim(ByVal str As String) As String

To remove the empty spaces from both sides of a string, you can call the Trim() function. Itssyntax is:

Public Shared Function Trim(ByVal str As String) As String

Creating an Empty Spaced String

If you want to create a string made of one or more empty spaces, you can call the Space()function. Its syntax is:

Public Shared Function Space(ByVal Number As Integer) As String

This function is the programmatic equivalent to pressing the Space bar when typing a string toinsert an empty space between two characters.

Strings Comparisons

To compare two strings, you can call the StrCmp() function. Its syntax is:

Public Shared Function StrComp( _ ByVal String1 As String, _ ByVal String2 As String, _ <Microsoft.VisualBasic.OptionCompareAttribute> _ Optional ByVal Compare As Microsoft.VisualBasic.CompareMethod _) As Integer

The first and the second arguments to this function are strings and both are required. After thefunction has performed the comparison, it returns

-1 if string1 is less than string2

0 if string1 and string2 are equal

1 if string1 is greater than string2

The third argument allows you to specify the comparison in binary or text format. This argumentcan have one of the following values:

Constant Value Description

vbBinaryCompare 0 Perform a binary comparison

vbTextCompare 1 Perform a textual comparison

Here is an example:

Private Sub cmdCreate_Click() Dim strValue1 As String Dim strValue2 As String Dim iComparisonValue strValue1 = "République d'Afrique du Sud" strValue2 = "Republic of South Africa" iComparisonValue = StrComp(strValue1, strValue2, vbTextCompare) MsgBox "Comparing """ & strValue1 & """ with """ & _ strValue2 & """ produces " & CStr(iComparisonValue)End Sub

This would produce:

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 111: Microsoft Visual Basic 2010 Tutorial

Home Copyright © 2008-2010 FunctionX

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 112: Microsoft Visual Basic 2010 Tutorial

Incrementing and Decrementing Values

Incrementing a Variable

We are used to counting numbers such as 1, 2, 3, 4, etc. In reality, when counting suchnumbers, we are simply adding 1 to a number in order to get the next number in the range. Thesimplest technique of incrementing a value consists of adding 1 to it. After adding 1, the value orthe variable is (permanently) modified and the variable would hold the new value. This isillustrated in the following example:

Module Exercise

Public Function Main() As Integer Dim Value As Integer

Value = InputBox("Enter the Value:")

MsgBox(Value)

Value = Value + 1

MsgBox(Value)

Return 0 End Function

End Module

This would produce:

Decrementing a Value

When counting numbers backward, such as 8, 7, 6, 5, etc, we are in fact subtracting 1 from avalue in order to get the lesser value. This operation is referred to as decrementing a value. Thisoperation works as if a value is decremented by 1, as in Value = Value - 1:

Module Exercise

Public Function Main() As Integer Dim Value As Integer

Value = InputBox("Enter the Value:")

MsgBox(Value)

Value = Value - 1

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 113: Microsoft Visual Basic 2010 Tutorial

MsgBox(Value)

Return 0 End Function

End Module

This would produce:

Techniques of Incrementing and Decrementing a Variable

It is not unusual to add or subtract a constant value to or from a variable. All you have to do is todeclare another variable that would hold the new value. Here is an example:

Module Exercise

Public Function Main() As Integer Dim Value As Double = 12.75

MsgBox("Value = " & Value)

Value = Value + 2.42

MsgBox("Value = " & Value)

Return 0 End Function

End Module

This would produce:

The above technique requires that you use an extra variable in your application. The advantage isthat each value can hold its own value although the value of the second variable depends onwhatever would happen to the original or source variable.

Sometimes in your program you will not need to keep the original value of the source variable.You may want to permanently modify the value that a variable is holding. In this case you can

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 114: Microsoft Visual Basic 2010 Tutorial

perform the addition operation directly on the variable by adding the desired value to the variable.This operation modifies whatever value a variable is holding and does not need an additionalvariable.

To add a value to a variable and change the value that the variable is holding, you can combinethe assignment = and the addition + operators to produce a new operator as +=

Here is an example:

Module Exercise

Public Function Main() As Integer Dim Value As Double = 12.75

MsgBox("Value = " & Value)

Value += 2.42

MsgBox("Value = " & Value)

Return 0 End Function

End Module

This program produces the same result as the previous. To decrement the value of a variable,instead of the addition, use the subtraction and apply the same technique. In the above program,the variable can have its value decremented by combining the assignment and the subtractionoperations on the variable. This is done with the -= operator. Here is an example:

Module Exercise

Public Function Main() As Integer Dim Value As Double = 12.75

MsgBox("Value = " & Value)

Value -= 2.42

MsgBox("Value = " & Value)

Return 0 End Function

End Module

This would produce:

Home Copyright © 2010 FunctionX, Inc.

Created by www.ebooktutorials.blogspot.in

Content downloaded from www.functionx.com

Page 115: Microsoft Visual Basic 2010 Tutorial

Introduction to Procedures and Functions

Introduction to Procedures

A procedure is a small program that is meant to solve a relatively small problem. In fact,sometimes it is called a sub-program. A program developer writes the procedure and a user(the user is either you or another programmer) would only see the result. There are twocategories of procedures you will use in your programs: those that have already been createdthus made available to you, and those you will create yourself.

Creating a Procedure

You can create a procedure manually or, if you are using Microsoft Visual Studio, code can begenerated for you. To manually create a procedure, start by typing the Sub keyword followedby a name (like everything else, a procedure must have a name). At the end of theprocedure, you must type End Sub. Therefore, the primary formula of a procedure is:

Sub ProcedureName()

End Sub

The name of a procedure should follow the rules of names in the Visual Basic language. Inaddition:

If the procedure performs an action that can be represented with a verb, you can use thatverb to name it. Here are examples: show, display

To make the name of a procedure stand, you should start it in uppercase. Examples areShow, Play, Dispose, Close

You should use explicit names that identify the purpose of the procedure. If a procedurewould be used as a result of something, reflect it on the name of the sub procedure.Examples would be: afterupdate, longbefore.

If the name of a procedure is a combination of words, you should start each word inuppercase. Examples are: AfterUpdate, SayItLoud

To let the studio start a procedure for you, first create a module. In the body of the module,right-click and click Insert Snippet... In the menu, double-click Code Patterns, If, For Each,Property, etc... Double-click Properties, Procedures, Events. Double-click Define a Sub:

This would produce:

Module Exercise

Sub MySub()

End Sub

End Module

Page 116: Microsoft Visual Basic 2010 Tutorial

The section between the Sub and the End Sub lines is referred to as the body of the procedure.Here is an example:

Sub Assign()

End Sub

The body of the procedure is used to define what, and how, the assignment should be carried.For example, if you need to use a variable, you can declare it and specify the kind of variableyou need. There is no restriction on the type of variables that can be declared in a procedure.Here is an example in which a string variable is declared in the body of a procedure:

Sub Assign() Dim strFullName As StringEnd Sub

In the same way, you can declare as many variables as you need inside of a procedure. Theactions you perform inside of a procedure depend on what you are trying to accomplish. Forexample, a procedure can simply be used to create a string. The above procedure can bechanged as follows:

Sub Assign() Dim strFullName As String strFullName = "Paul Bertrand Yamaguchi"End Sub

Practical Learning: Introducing Procedures

1. Start Microsoft Visual Basic

2. To create a new application, on the main menu, click File -> New Project

3. In the middle list, click Console Application

4. In the Name text box, replace the name with Geometry1

5. Click OK

6. On the main menu, click Project -> Geormetry1 Properties

7. Click the arrow of the Application Type box and select Windows Forms Application

8. Click the Close button to close the Property Pages window

9. In the Solution Explorer, right-click Module1.vb and click Rename

10. Type Geometry.vb and press Enter

11. Still in the Solution Explorer, double-click Geometry.vb

12. To create a procedure, change the document as follows:

Public Module Geometry

Sub ProcessSquare() Dim dblSide As Double Dim dblPerimeter As Double

dblSide = InputBox("Enter Side: ")

dblPerimeter = dblSide * 4

MsgBox("=-= Square Characteristics=-=" & vbCrLf & "Side: " & dblSide & vbCrLf & "Perimeter: " & dblPerimeter) End Sub

Sub Main()

End Sub

End Module

Calling a Sub Procedure

Once you have a procedure, whether you created it or it is part of the Visual Basic language, youcan use it. Using a procedure is also referred to as calling it. Before calling a procedure, youshould first locate the section of code in which you want to use it. To call a simple procedure,type its name followed by parentheses in the section where you want to use it. Here is anexample:

Module Exercise

Sub Assign() Dim strFullName As String strFullName = "Paul Bertrand Yamaguchi"

MsgBox(strFullName)

Page 117: Microsoft Visual Basic 2010 Tutorial

End Sub

Friend Sub Main() Assign() End Sub

End Module

Besides using the name of a procedure to call it, you can also precede it with the Call keyword.Here is an example:

Module Exercise

Sub Assign() Dim strFullName As String strFullName = "Paul Bertrand Yamaguchi"

MsgBox(strFullName) End Sub

Friend Sub Main() Call Assign() End Sub

End Module

Practical Learning: Calling a Sub Procedure

1. To call the procedure, type its name in the Main() procedure as follows:

Module Central

Sub ProcessSquare() Dim dblSide As Double Dim dblPerimeter As Double

dblSide = InputBox("Enter Side: ")

dblPerimeter = dblSide * 4

MsgBox("=-= Square Characteristics=-=" & vbCrLf & "Side: " & dblSide & vbCrLf & "Perimeter: " & dblPerimeter) End Sub

Sub Main() ProcessSquare() End Sub

End Module

2. To execute the program, on the Standard toolbar, click the Start Debugging button

3. Enter the side of the square as 48.14

4. Click OK to close the message box and return to your programming environment

Procedures and Access Modifiers

Like a variable, a procedure can use access modifiers. A procedure can be made a privateprocedure, a friendly procedure, or a public procedure, using the Private, the Friend, or thePublic keywords respectively:

Private: A procedure marked as private can be called only by members of the same module

Friend: A friendly procedure can be called by members of the modules of the sameapplication

Public: A public procedure can be called from its program and other programs

Practical Learning: Access Modifying a Procedure

Page 118: Microsoft Visual Basic 2010 Tutorial

1. To control the access to a procedure, change the file as follows:

Public Module Geometry

Private Sub ProcessSquare() Dim dblSide As Double Dim dblPerimeter As Double

dblSide = InputBox("Enter Side: ")

dblPerimeter = dblSide * 4

MsgBox("=-= Square Characteristics =-=" & vbCrLf & "Side: " & dblSide & vbCrLf & "Perimeter: " & dblPerimeter) End Sub

Public Sub Main() ProcessSquare() End Sub

End Module

2. To execute the program, on the main menu, click Debug -> Start Debugging

3. Enter the side of the square as 105.15

4. Close the message box and return to your programming environment

Introduction to Functions

Introduction

Like a procedure, a function is a sub-program used to perform an assignment. The maindifference between a procedure and a function is that, after carrying its assignment, a functiongives back a result. We also say that a function "returns a value". To distinguish both, there isa different syntax you use for a function.

Creating a Function

You can manually create a function or, if you are using Microsoft Visual Basic, ask it to createcode for you.

To manually create a function, you use the Function keyword followed by a name andparentheses. Unlike a procedure, because a function returns a value, you must specify the typeof value the function will produce. To give this information, on the right side of the closingparenthesis, you can type the As keyword, followed by a data type. To indicate where a functionstops, type End Function. As seen for a procedure, a function can have an access modifier.The rules for access modifiers are the same as we described for a procedure.

If you are using Microsoft Visual Basic and you want the studio to generate code for you, right-click inslde a module and click Insert Snippet... In the menu, double-click Code Patterns, If, ForEach, Property, etc... Double-click Properties, Procedures, Events. Double-click Define aFunction.

The minimum formula used to create a function is:

AccessModifier(s) Function FunctionName() As DataType End Function

The Function keyword is required. The name of a function follows the same rules andsuggestions we reviewed for sub procedures. The As keyword may be required (in the nextsections, we will review the alternatives to the As DataType expression).

The DataType indicates the type of value the function will return. If the function will produce aword or a group of words, you can create it as String. The other data types are also valid inthe contexts we reviewed them. Here is an example:

Function GetFullName() As String End Function

As done with the variables, you can also use a type character as the return type of a functionand omit the As DataType expression. The type character is typed on the right side of thefunction name and before the opening parenthesis. An example would be GetFullname$(). Aswith the variables, you must use the appropriate type character for the function:

Character The function must return$ a String type

Page 119: Microsoft Visual Basic 2010 Tutorial

% a Byte, Short, Int16, or In32& an Int64 or a Long! a Single type# a Double@ a Long integer

Here is an example:

Function GetFullName$()

End Function

As mentioned already, the section between the Function and the End Function lines is thebody of the function. It is used to describe what the function does. As done on a subprocedure, one of the actions you can perform in a function is to declare a (local) variable anduse it as you see fit. Here is an example:

Function CallMe() As String Dim Salute As String Salute = "You can call me Al"End Function

Returning a Value From a Function

After performing an assignment in a function, to indicate the value it returns, somewhere afterthe assignment and before the End Function line, you can type the name of the function,followed by the = sign, followed by the value the function returns. Here is an example in whicha function returns a name:

Function GetFullName$() Dim FirstName As String, LastName As String

FirstName = InputBox("Enter First Name: ") LastName = InputBox("Enter Last Name: ")

GetFullName = LastName & ", " & FirstNameEnd Function

Alternatively, instead of using the name of the function to indicate the value it returns, you cantype Return, followed by the value or the expression that the function returns. Based on this,the above function could also be created as follows:

Function GetFullName$() Dim FirstName As String, LastName As String

FirstName = InputBox("Enter First Name: ") LastName = InputBox("Enter Last Name: ")

Return LastName & ", " & FirstNameEnd Function

You can also use some local variables in the function to perform an assignment and then assigntheir result to the name of the function.

New Convention:

From now on, in our lessons, to refer to a procedure or function, we will use the name of aprocedure followed by parentheses. For example, we may write "the Convert() procedure" or"the Convert() function".

Practical Learning: Creating a Function

To create a function, change the file as follows:

Module Geometry

Private Sub ProcessSquare() Dim dblSide As Double Dim dblPerimeter As Double

dblSide = InputBox("Enter Side: ")

dblPerimeter = dblSide * 4

MsgBox("=-= Square Characteristics=-=" & vbCrLf & "Side: " & dblSide & vbCrLf & "Perimeter: " & dblPerimeter) End Sub

Private Function CalculatePerimeter() As Double Dim dblLength As Double Dim dblWidth As Double

Page 120: Microsoft Visual Basic 2010 Tutorial

dblLength = InputBox("Enter Rectangle Length: ") dblWidth = InputBox("Enter Rectangle Width: ")

CalculatePerimeter = (dblLength + dblWidth) * 2 End Function

Public Sub Main()

End Sub

End Module

Calling a Function

As done for the sub procedure, in order to use a function in your program, you must call it. Likea sub procedure, to call a function, you can simply type its name in the desired section of theprogram. Here is an example:

Sub Main() CallMeEnd Sub

Since the primary purpose of a function is to return a value, to better take advantage of such avalue, you can assign the name of a function to a variable in the section where you are callingthe function. Here is an example:

Module Exercise

Function GetFullName$() Dim FirstName As String, LastName As String

FirstName = InputBox("Enter First Name: ") LastName = InputBox("Enter Last Name: ")

Return LastName & ", " & FirstName End Function

Friend Sub Main() Dim FullName$

FullName = GetFullName() MsgBox(FullName) End Sub

End Module

Here is an example of running this program:

Practical Learning: Calling a Function

1. To call a function, change the file as follows:

Public Module Rectangle

Private Function CalculatePerimeter() As Double Dim dblLength As Double Dim dblWidth As Double

Page 121: Microsoft Visual Basic 2010 Tutorial

dblLength = InputBox("Enter Rectangle Length: ") dblWidth = InputBox("Enter Rectangle Width: ")

CalculatePerimeter = (dblLength + dblWidth) * 2 End Function

Public Sub Main() Dim Perimeter As Double

Perimeter = CalculatePerimeter()

MsgBox("=-= Square Characteristics=-=" & vbCrLf & "Perimeter: " & Perimeter) End Sub

End Module

2. To execute the program, on the Standard toolbar, click the Start Debugging button

3. Enter the length as 25.52 and the width as 20.84

4. Close the message box to return to your programming environment

The Main() Procedure

The Visual Basic Language uses a special procedure and function called Main. Main is the entrypoint of a program as we have used it so far. Particularly, Main can be used as a procedure ora function. So far, we have used Main only as a procedure. To use Main as a function, type theFunction keyword required for each function, followed by Main(), followed by As Integer.When declared like this, the Main function must return an integer. The most regularly returnvalue is 0, which indicates that the function ended successfully. Here is an example:

Module Exercise

Friend Function GetFullName$() Dim FirstName As String, LastName As String

FirstName = InputBox("Enter First Name: ") LastName = InputBox("Enter Last Name: ")

Return LastName & ", " & FirstName End Function

Friend Function Main() As Integer Dim FullName$

FullName = GetFullName() MsgBox(FullName)

Return 0 End Function

End Module

Practical Learning: Using the Main Function

1. To use Main() as a function, change it as follows:

Module Geometry

Private Sub ProcessSquare() Dim dblSide As Double Dim dblPerimeter As Double

dblSide = InputBox("Enter Side: ")

dblPerimeter = dblSide * 4

MsgBox("=-= Square Characteristics=-=" & vbCrLf & "Side: " & dblSide & vbCrLf & "Perimeter: " & dblPerimeter) End Sub

Private Function CalculatePerimeter() As Double Dim dblLength As Double Dim dblWidth As Double

dblLength = InputBox("Enter Rectangle Length: ") dblWidth = InputBox("Enter Rectangle Width: ")

CalculatePerimeter = (dblLength + dblWidth) * 2 End Function

Public Function Main() As Integer Dim Perimeter As Double

Perimeter = CalculatePerimeter()

MsgBox("=-= Square Characteristics=-=" & vbCrLf &

Page 122: Microsoft Visual Basic 2010 Tutorial

"Perimeter: " & Perimeter)

Return 0 End Function

End Module

2. To execute the program, on the Standard toolbar, click the Start Debugging button

3. Enter the length as 88.16 and the width as 44.14

4. Close the message box and return to your programming environment

Maintenance of Procedures

Introduction

Depending on an author, in the Visual Basic language, the word "procedure" includes either aprocedure created with the Sub keyword, or a function created with the Function keyword. Inthe same way, for the rest of our lessons, the word procedure will be used to represent bothtypes. Only when we want to be precise will we use the expression "a procedure" or "a sub-procedure" to explicitly mean the type of procedure that does not return a value. When theword "function" is used in our lessons, it explicitly refers to the type of procedure that returns avalue.

Accessing a Procedure

If you are using a text editor to write your code, you can use the Edit main menu to do asearch on the name of the procedure. If you are using Microsoft Visual Basic, in the top sectionof the Class View, click the name of the module in which the procedure exists. In the bottomsection of the Class View, double-click the name of the procedure. The Code Editor would jumpto where the procedure was defined. As an alternative, if you see a section where theprocedure gets called in the Code Editor, right-click its name and click Go To Definition. Thiswould select the name of the procedure where it is defined.

Renaming a Procedure

You can rename a procedure the same you would proceed for a variable. If you are using a texteditor like Notepad, you can do a search on its name and replace all instances with a newname. If you are using Microsoft Visual Basic, Find the name of the procedure where it isdefined and change it:

Then click the button under the new name, click the arrow on the button and click Rename.

Home Copyright © 2008-2010 FunctionX Next

Page 123: Microsoft Visual Basic 2010 Tutorial
Page 124: Microsoft Visual Basic 2010 Tutorial

Passing Arguments

Using Global Variables

In the previous lesson, we saw that you could declare a global variable outside of anyprocedure. When using various procedures in a code file, one of the characteristics of a globalvariable is that it is automatically accessible to other procedures. Still, a global variable canuse access modifiers that would control its access:

Private: A private global variable can be accessed by any procedure of the same module.No procedure of another module, even of the same program, can access it

Friend: A friendly global variable can be accessed by any procedure of any module of thesame project. A procedure of another program cannot access that variable

Public: A public global variable can be accessed by any procedure of its project andprocedures of other projects

Page 125: Microsoft Visual Basic 2010 Tutorial

Based on this characteristic of the procedures of a module having access to global variables ofthe same program, you can declare such variables and initialize or modify them in any procedureof the same code file.

Practical Learning: Using Global Variables

1. To use global variables, change the document as follows:

Module Geometry Private Length As Double Private Width As Double

Private Sub GetLength() Length = InputBox(&quot;Enter Rectangle Length:&quot;) End Sub

Private Sub GetWidth() Width = InputBox(&quot;Enter Rectangle Width:&quot;) End Sub

Private Function CalculatePerimeter() As Double CalculatePerimeter = (Length + Width) * 2 End Function

Public Function Main() As Integer Dim Perimeter As Double GetLength() GetWidth() Perimeter = CalculatePerimeter()

MsgBox("=-= Square Characteristics=-=" & vbCrLf & "Length: " & vbTab & Length & vbCrLf & "Width: " & vbTab & Width & vbCrLf & "Perimeter: " & Perimeter) Return 0 End Function

End Module

2. To execute the program, on the Standard toolbar, click the Start Debugging button

3. Enter the length as 32.08 and the with as 24.84

4. Close the message box and return to your programming environment

Introduction to Arguments

So far, to use a value in a procedure, we had to declare it. In some cases, a procedure mayneed an external value in order to carry its assignment. A value that is supplied to a procedureis called an argument.

When creating a procedure that will use an external value, declare the argument that representsthat value between the parentheses of the procedure. For a procedure, the syntax you usewould be:

Sub ProcedureName(Argument) End Sub

If you are creating a function, the syntax would be:

Function ProcedureName(Argument) As DataType Function Sub

Page 126: Microsoft Visual Basic 2010 Tutorial

The argument must be declared as a normal variable, omitting the Dim keyword. Here is anexample that creates a function that takes a string as argument:

Function CalculatePayroll(strName As String) As Double Function Sub

A certain procedure can take more than one argument. In this case, in the parentheses of theprocedure, separate the arguments with a comma. Here is an example of a procedure that takestwo arguments:

Sub EvaluateInvoice(EmplName As String, HourlySalary As Currency) End Sub

In the body of a procedure that takes one or more arguments, use the argument(s) as you seefit as if they were locally declared variables. For example, you can involve them with valuesinside of the procedure. You can also exclusively use the values of the arguments to perform theassignment.

Calling a Procedure With Argument

To call a procedure that takes an argument, type its name and a space, followed by a value foreach argument between parentheses. The value provided for an argument is also called aparameter. If there is more than one argument, separate them with a comma. Here is anexample:

Module Exercise

Private Function GetFullName$(strFirst As String, strLast As String) Dim FName As String

FName = strFirst & " " & strLast GetFullName = FName End Function

Public Function Main() As Integer Dim FirstName, LastName As String Dim FullName As String Dim ComputerLanguage As String = "Visual Basic"

FirstName = inputbox("Enter First Name: ") LastName = inputbox("Enter Last Name: ")

FullName = GetFullName(FirstName, LastName)

msgbox("Hello, " & FullName) Welcome(ComputerLanguage) Return 0 End Function

Sub Welcome(ByVal strLanguage As String) msgbox("Welcome to the wonderful world of " & strLanguage) End Sub

End Module

As mentioned previously, you can also use the Call keyword to call a procedure.

When you call a procedure that takes more than one argument, you must provide the values ofthe arguments in the exact order they are listed inside of the parentheses of the function.Fortunately, you don't have to. If you know the names of the arguments, you can type them inany order and provide a value for each. To do that, on the right side of each argument, type the:= operator followed by the desired value for the argument. Here are examples:

Public Module Exercise

Private Function GetFullName$(MI As String, LastName As String, FirstName As String) GetFullName = FirstName & " " & MI & " " & LastName End Function

Public Function Main() As Integer Dim FullName As String Dim ComputerLanguage As String = "VBasic"

FullName = GetFullName(LastName:="Roberts", FirstName:="Alan", MI:="R.")

MsgBox("Hello " & FullName) Call Welcome(ComputerLanguage) Return 0 End Function

Private Sub Welcome(ByVal strLanguage As String) MsgBox("Welcome to the wonderful world of " & strLanguage) End Sub

Page 127: Microsoft Visual Basic 2010 Tutorial

End Module

Practical Learning: Passing Arguments to a Procedure

1. To pass arguments to a function, change the file as follows (when you type the argument,Microsoft Visual Studio, actually the Visual Basic language parser, will add the ByValkeywords; in the next sections, we will learn what that keyword means; for now, keep it butignore it):

Module Geometry Private Function GetValue(TypeOfValue As String) As Double Dim Value As Double

Value = InputBox("Enter the " & TypeOfValue & ":") Return Value End Function

Private Function CalculatePerimeter(ByVal Length As Double, ByVal Width As Double) As Double CalculatePerimeter = (Length + Width) * 2 End Function

Public Function Main() As Integer Dim L As Double, W As Double Dim Perimeter As Double

L = GetValue("Length") W = GetValue("Width") Perimeter = CalculatePerimeter(L, W)

MsgBox("=-= Square Characteristics=-=" & vbCrLf & "Length: " & L & vbCrLf & "Width: " & W & vbCrLf & "Perimeter: " & Perimeter) Return 0 End Function

End Module

2. To execute the program, on the main menu, click Debug -> Start Debugging

3. Enter the length as 44.14 and the with as 30.76

4. Close the message box and return to your programming environment

Techniques of Passing Arguments

Passing an Argument By Value

When calling a procedure that takes an argument, we were supplying a value for thatargument. When this is done, the procedure that is called makes a copy of the value of theargument and makes that copy available to the calling procedure. That way, the argument itselfis not accessed. This is referred to as passing an argument by value. This can be reinforced bytyping the ByVal keyword on the left side of the argument. Here is an example:

Private Sub Welcome(ByVal strLanguage As String) MsgBox("Welcome to the wonderful world of " & strLanguage)End Sub

If you create a procedure that takes an argument by value and you have used the ByValkeyword on the argument, when calling the procedure, you don't need to use the ByValkeyword; just the name of the argument is enough, as done in the examples on arguments sofar. Here is an example:

Public Module Exercise

Public Function Main() As Integer Dim ComputerLanguage As String = "Visual Basic"

Welcome(ComputerLanguage) Return 0 End Function

Private Sub Welcome(ByVal strLanguage As String) MsgBox("Welcome to the wonderful world of " & strLanguage) End Sub

End Module

This would produce:

Page 128: Microsoft Visual Basic 2010 Tutorial

Passing an Argument By Reference

An alternative to passing an argument as done so far is to pass the address of the argument tothe procedure. When this is done, the procedure doesn't receive a simple copy of the value ofthe argument: the argument is accessed by its address. That is, at its memory address. Withthis technique, any action carried on the argument will be kept. If the value of the argument ismodified, the argument would now have the new value, dismissing or losing the original value ithad. This technique is referred to as passing an argument by reference. Consider the followingprogram:

Public Module Exercise

Private Function Addition#(ByVal Value1 As Double, ByVal Value2 As Double) Value1 = InputBox("Enter First Number: ") Value2 = InputBox("Enter Second Number: ")

Addition = Value1 + Value2 End Function

Public Function Main() As Integer Dim Result As String Dim Number1, Number2 As Double

Result = Addition(Number1, Number2) MsgBox(Number1 & " + " & Number2 & " = " & Result) Return 0 End Function

End Module

Here is an example of running the program:

Notice that, although the values of the arguments were changed in the Addition() procedure, atthe end of the procedure, they lose the value they got in the function. If you want a procedureto change the value of an argument, you can pass the argument by reference.

To pass an argument by reference, on its left, type the ByRef keyword. This is done only whendefining the procedure. When the procedure finishes with the argument, the argument wouldkeep whatever modification was made on its value. Now consider the same program as abovebut with arguments passed by reference:

Public Module Exercise

Private Function Addition#(ByRef Value1 As Double, ByRef Value2 As Double) Value1 = InputBox("Enter First Number: ") Value2 = InputBox("Enter Second Number: ")

Page 129: Microsoft Visual Basic 2010 Tutorial

Addition = Value1 + Value2 End Function

Public Function Main() As Integer Dim Result As String Dim Number1, Number2 As Double

Result = Addition(Number1, Number2) MsgBox(Number1 & " + " & Number2 & " = " & Result) Return 0 End Function

End Module

Here is an example of running the program:

Using this technique, you can pass as many arguments by reference and as many arguments byvalue as you want. As you may guess already, this technique is also used to make a procedurereturn a value, which a regular procedure cannot do. Furthermore, passing arguments byreference allows a procedure to return as many values as possible while a regular function canreturn only one value.

Practical Learning: Passing Arguments by Reference

1. To pass an argument by reference, change the file as follows:

Module Geometry Private Sub GetValues(ByRef Length As Double, ByRef Width As Double) Length = InputBox("Enter the length:") Width = InputBox("Enter the width:") End Sub

Private Function CalculatePerimeter(ByVal Length As Double, ByVal Width As Double) As Double CalculatePerimeter = (Length + Width) * 2 End Function

Private Function CalculateArea(ByVal Length As Double, _ ByVal Width As Double) As Double CalculateArea = Length * Width End Function

Private Sub ShowCharacteristics(ByVal Length As Double, ByVal Width As Double) Dim Result As String

Result = "=-= Rectangle Characteristics =-=" & vbCrLf & "Length: " & vbTab & vbTab & CStr(Length) & vbCrLf & "Width: " & vbTab & vbTab & CStr(Width) & vbCrLf & "Perimeter: " & vbTab & CalculatePerimeter(Length, Width) & vbCrLf & "Area: " & vbTab & vbTab & CalculateArea(Length, Width) MsgBox(Result) End Sub

Public Function Main() As Integer Dim L As Double, W As Double

Page 130: Microsoft Visual Basic 2010 Tutorial

GetValues(L, W) ShowCharacteristics(L, W)

Return 0 End Function

End Module

2. To execute the program, on the Standard toolbar, click the Start Debugging button

3. Enter the length as 24.55 and the width as 22.85

4. Close the message box and return to your programming environment

Other Techniques of Passing Arguments

Optional Arguments

If you create a procedure that takes one or more arguments, whenever you call that procedure,you must provide a value for the argument(s). Otherwise,, you would receive an error. If suchan argument is passed with the same value over and over again, you may be tempted toremove the argument altogether. In some cases, although a certain argument is passed withthe same value most of the time, you still have situations in which you want the user to decidewhether to pass a value or not for the argument, you can declare the value optional. In otherwords, you can create the argument with a default value so that the user can call the procedurewithout passing a value for the argument, thus passing a value only when necessary. Such anargument is called default or optional.

Imagine you write a procedure that will be used to calculate the final price of an item afterdiscount. The procedure would need the discount rate in order to perform the calculation. Sucha procedure could look like this:

Function CalculateNetPrice#(ByVal DiscountRate As Double) Dim OrigPrice#

OrigPrice = InputBox("Please enter the original price:")

Return OrigPrice - (OrigPrice * DiscountRate / 100)End Function

Since this procedure expects an argument, if you do not supply it, the following program wouldnot compile:

Public Module Exercise

Function CalculateNetPrice#(ByVal DiscountRate As Double) Dim OrigPrice#

OrigPrice = InputBox("Please enter the original price:")

Return OrigPrice - (OrigPrice * DiscountRate / 100) End Function

Public Function Main() As Integer Dim FinalPrice# Dim Discount# = 15 ' That is 25% = 25

FinalPrice = CalculateNetPrice(Discount)

MsgBox("Final Price = " & FinalPrice) Return 0 End Function

End Module

Here is an example of running the program:

Page 131: Microsoft Visual Basic 2010 Tutorial

Most of the time, a procedure such as ours would use the same discount rate over and overagain. Therefore, instead of supplying an argument all the time, you can define an argumentwhose value would be used whenever the function is not provided with the argument.

To specify that an argument is optional, when creating its procedure, type the Optionalkeyword to the left of the argument's name and assign it the default value. Here is anexample:

Public Module Exercise

Function CalculateNetPrice#(Optional ByVal DiscountRate As Double = 20) Dim OrigPrice#

OrigPrice = InputBox("Please enter the original price:")

Return OrigPrice - (OrigPrice * DiscountRate / 100) End Function

Public Function Main() As Integer Dim FinalPrice# Dim Discount# = 15 ' That is 25% = 25

FinalPrice = CalculateNetPrice()

MsgBox("Final Price = " & FinalPrice) Return 0 End Function

End Module

Here is an example of running the program:

If a procedure takes more than one argument, you can provide a default argument for each andselect which ones would have default values. If you want all arguments to have default values,when defining the procedure , provide the Optional keyword for each and assign it the desireddefault value. Here is an example:

Public Module Exercise

Function CalculateNetPrice#(Optional ByVal Tax As Double = 5.75, Optional ByVal Discount As Double = 25, Optional ByVal OrigPrice As Double = 245.55) Dim DiscountValue As Double = OrigPrice * Discount / 100 Dim TaxValue As Double = Tax / 100 Dim NetPrice As Double = OrigPrice - DiscountValue + TaxValue Dim Result As String

Result = "Original Price: " & vbTab & CStr(OrigPrice) & vbCrLf & "Discount Rate: " & vbTab & CStr(Discount) & "%" & vbCrLf &

Page 132: Microsoft Visual Basic 2010 Tutorial

"Tax Amount: " & vbTab & CStr(Tax) MsgBox(Result)

Return NetPrice End Function

Public Function Main() As Integer Dim FinalPrice As Double

FinalPrice = CalculateNetPrice() MsgBox("Final Price: " & CStr(FinalPrice)) Return 0 End Function

End Module

This would produce:

If a procedure takes more than one argument as above, remember that some arguments canbe specified as optional. In this case, when calling the procedure, any argument that does nothave a default value must be passed with a value. When creating a procedure that takes morethan one argument, the argument(s) that has(have) default value(s) must be the last in theprocedure. This means that:

If a procedure takes two arguments and one argument has a default value, this optionalargument must be the second

If a procedure is taking three or more arguments and two or more arguments have defaultvalues, these optional arguments must by placed to the right of the non-optionalargument(s).

Because of this, when calling any procedure in the Visual Basic language, you must know what,if any, argument is optional and which one is not.

If a procedure takes two arguments and one argument has a default value, when calling thisprocedure, you can pass only one value. In this case, the passed value would be applied on thefirst argument. If a procedure takes more than two arguments and two or more argumentshave a default value, when calling this procedure, you can provide only the value(s) of theargument that is (are) not optional. If you want to provide the value of one of the argumentsbut that argument is not the first optional, you can leave empty the position(s) of the otherargument(s) but remember to type a comma to indicate that the position is that of anargument that has a default value. Here is an example:

Public Module Exercise

Function CalculateNetPrice(ByVal AcquiredPrice As Double, ByVal MarkedPrice As Double, Optional ByVal TaxRate As Double = 5.75, Optional ByVal DiscountRate As Double = 25) As Double Dim DiscountAmount As Double = MarkedPrice * DiscountRate / 100 Dim TaxAmount As Double = MarkedPrice * TaxRate / 100 Dim NetPrice As Double = MarkedPrice - DiscountAmount + TaxAmount Dim Result As String

Result = "Price Acquired: " & vbTab & CStr(AcquiredPrice) & vbCrLf & "Marked Price: " & vbTab & CStr(MarkedPrice) & vbCrLf & "Discount Rate: " & vbTab & CStr(DiscountRate) & "%" & vbCrLf & "Discount Amt: " & vbTab & CStr(DiscountAmount) & vbCrLf & "Tax Rate: " & vbTab & CStr(TaxRate) & "%" & vbCrLf & "Tax Amount: " & vbTab & CStr(TaxAmount) MsgBox(Result)

Return NetPrice End Function

Public Function Main() As Integer Dim FinalPrice As Double

Page 133: Microsoft Visual Basic 2010 Tutorial

FinalPrice = CalculateNetPrice(225.55, 150.55, , 40) MsgBox("Final Price: " & CStr(FinalPrice)) Return 0 End Function

End Module

This would produce:

Procedure Overloading

A program involves a great deal of names that represent variables and procedures of variouskinds. The compiler does not allow two variables to have the same name in the same procedure(or in the same scope). Although two procedures should have unique names in the sameprogram, you are allowed to use the same name for different procedures of the same programfollowing certain rules.

The ability to have various procedures with the same name in the same program is referred toas overloading. The most important rule about procedure overloading is to make sure that eachone of these procedures has a different number or different type(s) of arguments.

Practical Learning: Overloading a Procedure

The moment of inertia is the ability of a beam to resist bending. It is calculated with regard tothe cross section of the beam. Because it depends on the type of section of the beam, itscalculation also depends on the type of section of the beam. In this exercise, we will reviewdifferent formulas used to calculate the moment of inertia. Since this exercise is fordemonstration purposes, you do not need to be a Science Engineering major to understand it.

1. To start a new project, on the main menu, click File -> New Project...

2. In the middle list, click Console Application

3. Change the Name to MomentOfInertia1

4. Click OK

5. In the Solution Explorer, right-click Module1.vb and click Rename

6. Type MomentOfInertia.vb and press Enter

7. To calculate the moment of inertia of a rectangle, change the file as follows:

Page 134: Microsoft Visual Basic 2010 Tutorial

Module MomentOfInertia

' Moment of Inertia ' Rectangle Private Function MomentOfInertia(ByVal b As Double, ByVal h As Double) As Double Return b * h * h * h / 3 End Function

Public Sub Main() Dim Base As Double, Height As Double

Base = InputBox("Enter the base of the Rectangle") Height = InputBox("Enter the height of the Rectangle")

MsgBox("Moment of inertia with regard to the X axis" & vbCrLf & "I = " & CStr(MomentOfInertia(Base, Height)) & "mm") End Sub

End Module

8. To execute the program, on the main menu, click Debug -> Start Debugging

9. Enter the base as 3.25

10. Enter the height as 2.85

11. Close the DOS window and return to your programming environment

12. Here are the formulas to calculate the moment of inertia for a semi-circle:

A circle, and thus a semi-circle, requires only a radius. Since the other versionof the MomentOfInertia() function requires two arguments, we can overload itby providing only one argument, the radius.

To calculate the moment of inertia of a rectangle, change the file as follows:

Module MomentOfInertia

' Moment of Inertia ' Rectangle Private Function MomentOfInertia(ByVal b As Double, ByVal h As Double) As Double Return b * h * h * h / 3 End Function

Page 135: Microsoft Visual Basic 2010 Tutorial

' Semi-Circle Function MomentOfInertia(ByVal R As Double) As Double Const PI As Double = 3.14159

Return R * R * R * R * PI / 8 End Function

Public Sub Main() ' Dim Base As Double, Height As Double Dim Radius As Double

' Base = InputBox("Enter the base of the Rectangle:") ' Height = InputBox("Enter the height of the Rectangle") ' MsgBox("Moment of inertia with regard to the X axis" & vbCrLf & _ ' "I = " & CStr(MomentOfInertia(Base, Height)) & "mm")

Radius = InputBox("Enter the radius of the semi-circle:")

MsgBox("Moment of inertia of a semi-circle with " & "regard to the X axis:" & vbCrLf & "I = " & CStr(MomentOfInertia(Radius)) & "mm") End Sub

End Module

13. To execute the program, on the Standard toolbar, click the Start Debugging button

14. Enter the radius as 6.35

15. Close the DOS window and return to your programming environment

16. On the main menu, click File -> Close Solution (Microsoft Visual Studio) or File -> CloseProject (Microsoft Visual Basic 2010 Express)

17. When asked whether you want to save, click Discard

Previous Copyright © 2008-2010 FunctionX Next

Page 136: Microsoft Visual Basic 2010 Tutorial

Visual Basic Built-In Functions:Conversions

Introduction

You may recall that when studying data types, we saw that each had a corresponding functionused to convert a string value or an expression to that type. As a reminder, the general syntaxof the conversion functions is:

ReturnType = FunctionName(Expression)

The Expression could be of any kind. For example, it could be a string or expression that wouldproduce a value such as the result of a calculation. The conversion function would take such avalue, string, or expression and attempt to convert it. If the conversion is successful, the functionwould return a new value that is of the type specified by the ReturnType in our syntax.

The conversion functions are as follows:

Function

Name Return Type Description

CBool Boolean Converts an expression into a Boolean value

CByte Byte Converts an expression into Byte number

CDbl Double Converts an expression into a floating-point number withdouble precision

CDec Decimal Converts an expression into a decimal number

CInt Integer Converts an expression into an integer (natural) number

CLng Long Converts an expression into a long integer (a largenatural) number

CObj Object Converts an expression into an Object type

CSByte SByte Converts an expression into a signed byte

CShort Short Converts an expression into a short integer

CSng Single Converts an expression into a floating-point number withsingle precision

CUInt UInt Converts an expression into an unsigned integer

CULng ULong Converts an expression into an unsigned long integer

CUShort UShort Converts an expression into an unsigned short integer

Type Conversion

Conversion functions allow you to convert a known value to a another type. Besides thesefunctions, the Visual Basic language provides a function named CType. Its syntax is:

CType(expression, typename)

As you can see, the CType() function takes two arguments. The first argument is the expressionor the value that you want to convert. An example could be name of a variable or a calculation:

CType(250.48 * 14.05, ...)

The second argument is the type of value you want to convert the first argument to. From whathave learned so far, this second argument can be one of the data types we reviewed in Lesson 3.Here is an example:

CType(250.48 * 14.05, Single)

If you choose one of the Visual Basic language's data types, the expression produced by the firstargument must be able to produce a value that is conform to the type of the second argument:

The conversion from the first argument to the type of the second argument must be possible:the value produced by the first must be convertible to the second arguments. For example, ifthe first argument is a calculation, the second argument must be a number-based data type.In the same way, you cannot convert a date to a number-based type

If the first argument is a number or the result of a calculation, its resulting value must belower than or up to the range of values of the second argument. Here is an example:

Public Module Exercise

Page 137: Microsoft Visual Basic 2010 Tutorial

Public Function Main() As Integer

MsgBox(CType(250.48 * 14.05, Single))

Return 0 End Function

End Module

This would produce:

If the first argument is a number or the result of a calculation that produces an integer or afloating-point number, its resulting value must be convertible to an integer or a floating pointnumber up to the range of values of the second argument. Here is an example:

Public Module Exercise

Public Function Main() As Integer

MsgBox(CType(7942.225 * 202.46, UInteger))

Return 0 End Function

End Module

This would produce:

If the first argument is a number or the result of a calculation that produces an integer or afloating-point number, the second argument is a number-based data type but whose rangecannot hold the resulting value of the first argument, the conversion would not be allowed (theconversion will fail):

After the CType() function has performed its conversion, it returns a value that is the samecategory as the second argument. For example, you can call a CType() function that converts anexpression to a long integer. Here is an example:

Public Module Exercise

Public Function Main() As Integer Dim Number As Long

Number = CType(7942.225 * 202.46, Long)

Return 0 End Function

End Module

The function can also return a different type, as long as its type can hold the value produced bythe expression. Here are two examples:

Page 138: Microsoft Visual Basic 2010 Tutorial

Public Module Exercise

Public Function Main() As Integer Dim Number As UInteger

Number = CType(7942.225 * 202.46, Long)

Return 0 End Function

End Module

Or

Public Module Exercise

Public Function Main() As Integer Dim Number As Single

Number = CType(7942.225 * 202.46, Long)

Return 0 End Function

End Module

If you try storing the returned value into a variable that cannot hold it, you would receive anerror:

Home Copyright © 2008-2010 FunctionX, Inc.

Page 139: Microsoft Visual Basic 2010 Tutorial

Static Variables

Introduction

Consider the following program:

Public Module Exercise

Private Sub Starter(ByVal y As Integer) Dim a As Double = 112.5 Dim b As Double = 175.25 Dim Result As String

a = a / y b = b + 2

Result = "y = " & vbTab & CStr(y) & vbCrLf & _ "a = " & vbTab & CStr(a) & vbCrLf & _ "b = " & vbTab & CStr(b) & vbCrLf & _ "b/a = " & vbTab & CStr(b / a) MsgBox(Result) End Sub

Public Function Main() As Integer Starter(2) Starter(2) Starter(2) Starter(2)

Return 0 End Function

End Module

When executed, this program would produce:

The Starter() procedure receives one argument passed when it is called. This procedure alsoreceives the same argument every time. Looking at the result, the argument passed to theprocedure and the local variables declared inside of the called procedure keep the same value

Page 140: Microsoft Visual Basic 2010 Tutorial

every time the procedure is called. That is, when the Starter() procedure exits, the values remainthe same.

We know that, when a procedure is defined, any variable declared locally belongs to the procedureand its influence cannot expand beyond the body of the procedure. If you want a locally declaredvariable to keep its changed value when its host procedure is exited, declare such a variable asstatic.

Declaring a Static Variable

To declare a static variable, type the Static keyword on the left of the Dim keyword. You shouldalways initialize a static variable before using it. To make the local variables of our Starter()function static, we can declare them as follows:

Public Module Exercise

Private Sub Starter(ByVal y As Integer) Static Dim a As Double = 112.5 Static Dim b As Double = 175.25

Dim Result As String

a = a / y b = b + 2

Result = "y = " & vbTab & CStr(y) & vbCrLf & _ "a = " & vbTab & CStr(a) & vbCrLf & _ "b = " & vbTab & CStr(b) & vbCrLf & _ "b/a = " & vbTab & CStr(b / a) MsgBox(Result) End Sub

Public Function Main() As Integer Starter(2) Starter(2) Starter(2) Starter(2)

Return 0 End Function

End Module

This time, when executing the program, it would produce:

Notice that, this time, each local variable keeps its newly changed value when the function exits.

Page 141: Microsoft Visual Basic 2010 Tutorial

Home Copyright © 2008-2010 FunctionX, Inc.

Page 142: Microsoft Visual Basic 2010 Tutorial

Optional Arguments

Introduction

If you create a procedure that takes one or more arguments, whenever you call that procedure,you must provide a value for the argument(s). Otherwise,, you would receive an error. If such anargument is passed with the same value over and over again, you may be tempted to removethe argument altogether.

In some cases, although a certain argument is passed with the same value most of the time, youstill have situations in which you want the user to decide whether to pass a value or not for theargument, you can declare the value optional. In other words, you can create the argument with adefault value so that the user can call the procedure without passing a value for the argument,thus passing a value only when necessary. Such an argument is called default or optional.

Imagine you write a procedure that will be used to calculate the final price of an item afterdiscount. The procedure would need the discount rate in order to perform the calculation. Such aprocedure could look like this:

Function CalculateNetPrice#(ByVal DiscountRate As Double) Dim OrigPrice#

OrigPrice = InputBox("Please enter the original price:")

Return OrigPrice - (OrigPrice * DiscountRate / 100)End Function

Since this procedure expects an argument, if you do not supply it, the following program wouldnot compile:

Public Module Exercise

Function CalculateNetPrice#(ByVal DiscountRate As Double) Dim OrigPrice#

OrigPrice = InputBox("Please enter the original price:")

Return OrigPrice - (OrigPrice * DiscountRate / 100) End Function

Public Function Main() As Integer Dim FinalPrice# Dim Discount# = 15 ' That is 25% = 25

FinalPrice = CalculateNetPrice(Discount)

MsgBox("Final Price = " & FinalPrice) Return 0 End Function

End Module

Here is an example of running the program:

Most of the time, a procedure such as ours would use the same discount rate over and over again.Therefore, instead of supplying an argument all the time, you can define an argument whose valuewould be used whenever the function is not provided with the argument.

Passing an Optional Argument

To specify that an argument is optional, when creating its procedure, type the Optional keyword

Page 143: Microsoft Visual Basic 2010 Tutorial

to the left of the argument's name and assign it the default value. Here is an example:

Public Module Exercise

Function CalculateNetPrice#(Optional ByVal DiscountRate As Double = 20) Dim OrigPrice#

OrigPrice = InputBox("Please enter the original price:")

Return OrigPrice - (OrigPrice * DiscountRate / 100) End Function

Public Function Main() As Integer Dim FinalPrice# Dim Discount# = 15 ' That is 25% = 25

FinalPrice = CalculateNetPrice()

MsgBox("Final Price = " & FinalPrice) Return 0 End Function

End Module

Here is an example of running the program:

A Procedure With Many Optional Arguments

If a procedure takes more than one argument, you can provide a default argument for each andselect which ones would have default values. If you want all arguments to have default values,when defining the procedure , provide the Optional keyword for each and assign it the desireddefault value. Here is an example:

Public Module Exercise

Function CalculateNetPrice#(Optional ByVal Tax As Double = 5.75, _ Optional ByVal Discount As Double = 25, _ Optional ByVal OrigPrice As Double = 245.55) Dim DiscountValue As Double = OrigPrice * Discount / 100 Dim TaxValue As Double = Tax / 100 Dim NetPrice As Double = OrigPrice - DiscountValue + TaxValue Dim Result As String

Result = "Original Price: " & vbTab & CStr(OrigPrice) & vbCrLf & _ "Discount Rate: " & vbTab & CStr(Discount) & "%" & vbCrLf & _ "Tax Amount: " & vbTab & CStr(Tax) MsgBox(Result)

Return NetPrice End Function

Public Function Main() As Integer Dim FinalPrice As Double

FinalPrice = CalculateNetPrice() MsgBox("Final Price: " & CStr(FinalPrice)) Return 0 End Function

End Module

This would produce:

Page 144: Microsoft Visual Basic 2010 Tutorial

If a procedure takes more than one argument as above, remember that some arguments can bespecified as optional. In this case, when calling the procedure, any argument that does not have adefault value must be passed with a value. When creating a procedure that takes more than oneargument, the argument(s) that has(have) default value(s) must be the last in the procedure. Thismeans that:

If a procedure takes two arguments and one argument has a default value, this optionalargument must be the second

If a procedure is taking three or more arguments and two or more arguments have defaultvalues, these optional arguments must by placed to the right of the non-optional argument(s).

Because of this, when calling any procedure in the Visual Basic language, you must know what, ifany, argument is optional and which one is not.

If a procedure takes two arguments and one argument has a default value, when calling thisprocedure, you can pass only one value. In this case, the passed value would be applied on thefirst argument. If a procedure takes more than two arguments and two or more arguments have adefault value, when calling this procedure, you can provide only the value(s) of the argument thatis (are) not optional. If you want to provide the value of one of the arguments but that argumentis not the first optional, you can leave empty the position(s) of the other argument(s) butremember to type a comma to indicate that the position is that of an argument that has a defaultvalue. Here is an example:

Public Module Exercise

Function CalculateNetPrice(ByVal AcquiredPrice As Double, _ ByVal MarkedPrice As Double, _ Optional ByVal TaxRate As Double = 5.75, _ Optional ByVal DiscountRate As Double = 25) As Double Dim DiscountAmount As Double = MarkedPrice * DiscountRate / 100 Dim TaxAmount As Double = MarkedPrice * TaxRate / 100 Dim NetPrice As Double = MarkedPrice - DiscountAmount + TaxAmount Dim Result As String

Result = "Price Acquired: " & vbTab & CStr(AcquiredPrice) & vbCrLf & _ "Marked Price: " & vbTab & CStr(MarkedPrice) & vbCrLf & _ "Discount Rate: " & vbTab & CStr(DiscountRate) & "%" & vbCrLf & _ "Discount Amt: " & vbTab & CStr(DiscountAmount) & vbCrLf & _ "Tax Rate: " & vbTab & CStr(TaxRate) & "%" & vbCrLf & _ "Tax Amount: " & vbTab & CStr(TaxAmount) MsgBox(Result)

Return NetPrice End Function

Public Function Main() As Integer Dim FinalPrice As Double

FinalPrice = CalculateNetPrice(225.55, 150.55, , 40) MsgBox("Final Price: " & CStr(FinalPrice)) Return 0 End Function

End Module

This would produce:

Page 145: Microsoft Visual Basic 2010 Tutorial

Home Copyright © 2008-2009 FunctionX, Inc.

Page 146: Microsoft Visual Basic 2010 Tutorial

Overloading a Procedure

Introduction

A program involves a great deal of names that represent variables and procedures of variouskinds. The compiler does not allow two variables to have the same name in the same procedure(or in the same scope). Although two procedures should have unique names in the sameprogram, you are allowed to use the same name for different procedures of the same programfollowing certain rules.

Overloading a Procedure

The ability to have various procedures with the same name in the same program is referred to asoverloading. The most important rule about procedure overloading is to make sure that each oneof these procedures has a different number or different type(s) of arguments.

Practical Learning: Overloading a Procedure

The moment of inertia is the ability of a beam to resist bending. It is calculated with regard to thecross section of the beam. Because it depends on the type of section of the beam, its calculationalso depends on the type of section of the beam. In this exercise, we will review different formulasused to calculate the moment of inertia. Since this exercise is for demonstration purposes, you donot need to be a Science Engineering major to understand it.

1. Start Microsoft Visual Basic and create a Console Application named MomentOfInertia1

2. In the Solution Explorer, right-click Module1.vb and click Rename

3. Type MomentOfInertia.vb and press Enter

4. To calculate the moment of inertia of a rectangle, change the file as follows:

Module MomentOfInertia

' Moment of Inertia ' Rectangle Private Function MomentOfInertia(ByVal b As Double, _ ByVal h As Double) As Double Return b * h * h * h / 3 End Function

Public Sub Main() Dim Base As Double, Height As Double

Base = InputBox("Enter the base of the Rectangle") Height = InputBox("Enter the height of the Rectangle")

MsgBox("Moment of inertia with regard to the X axis" & vbCrLf & _ "I = " & CStr(MomentOfInertia(Base, Height)) & "mm") End Sub

End Module

5. Execute the application

6. Enter the base as 3.25

Page 147: Microsoft Visual Basic 2010 Tutorial

7. Enter the height as 2.85

8. Close the DOS window and return to your programming environment

9. Here are the formulas to calculate the moment of inertia for a semi-circle:

A circle, and thus a semi-circle, requires only a radius. Since the other versionof the MomentOfInertia() function requires two arguments, we can overload itby providing only one argument, the radius.

To calculate the moment of inertia of a rectangle, change the file as follows:

Module MomentOfInertia

' Moment of Inertia ' Rectangle Private Function MomentOfInertia(ByVal b As Double, _ ByVal h As Double) As Double Return b * h * h * h / 3 End Function

' Semi-Circle Function MomentOfInertia(ByVal R As Double) As Double Const PI As Double = 3.14159

Return R * R * R * R * PI / 8 End Function

Public Sub Main() ' Dim Base As Double, Height As Double Dim Radius As Double

' Base = InputBox("Enter the base of the Rectangle:") ' Height = InputBox("Enter the height of the Rectangle") ' MsgBox("Moment of inertia with regard to the X axis" & vbCrLf & _ ' "I = " & CStr(MomentOfInertia(Base, Height)) & "mm")

Radius = InputBox("Enter the radius of the semi-circle:")

MsgBox("Moment of inertia of a semi-circle with " & _ "regard to the X axis:" & vbCrLf & _ "I = " & CStr(MomentOfInertia(Radius)) & "mm") End Sub

End Module

10. Execute the application

Page 148: Microsoft Visual Basic 2010 Tutorial

11. Enter the radius as 6.35

12. Close the DOS window and return to your programming environment

Home Copyright © 2008-2009 FunctionX, Inc.

Page 149: Microsoft Visual Basic 2010 Tutorial

Visual Basic Built-In Functions:Conversions

Introduction

You may recall that when studying data types, we saw that each had a corresponding functionused to convert a string value or an expression to that type. As a reminder, the general syntaxof the conversion functions is:

ReturnType = FunctionName(Expression)

The Expression could be of any kind. For example, it could be a string or expression that wouldproduce a value such as the result of a calculation. The conversion function would take such avalue, string, or expression and attempt to convert it. If the conversion is successful, the functionwould return a new value that is of the type specified by the ReturnType in our syntax.

The conversion functions are as follows:

Function

Name Return Type Description

CBool Boolean Converts an expression into a Boolean value

CByte Byte Converts an expression into Byte number

CDbl Double Converts an expression into a floating-point number withdouble precision

CDec Decimal Converts an expression into a decimal number

CInt Integer Converts an expression into an integer (natural) number

CLng Long Converts an expression into a long integer (a largenatural) number

CObj Object Converts an expression into an Object type

CSByte SByte Converts an expression into a signed byte

CShort Short Converts an expression into a short integer

CSng Single Converts an expression into a floating-point number withsingle precision

CUInt UInt Converts an expression into an unsigned integer

CULng ULong Converts an expression into an unsigned long integer

CUShort UShort Converts an expression into an unsigned short integer

Type Conversion

Conversion functions allow you to convert a known value to a another type. Besides thesefunctions, the Visual Basic language provides a function named CType. Its syntax is:

CType(expression, typename)

As you can see, the CType() function takes two arguments. The first argument is the expressionor the value that you want to convert. An example could be name of a variable or a calculation:

CType(250.48 * 14.05, ...)

The second argument is the type of value you want to convert the first argument to. From whathave learned so far, this second argument can be one of the data types we reviewed in Lesson 3.Here is an example:

CType(250.48 * 14.05, Single)

If you choose one of the Visual Basic language's data types, the expression produced by the firstargument must be able to produce a value that is conform to the type of the second argument:

The conversion from the first argument to the type of the second argument must be possible:the value produced by the first must be convertible to the second arguments. For example, ifthe first argument is a calculation, the second argument must be a number-based data type.In the same way, you cannot convert a date to a number-based type

If the first argument is a number or the result of a calculation, its resulting value must belower than or up to the range of values of the second argument. Here is an example:

Public Module Exercise

Page 150: Microsoft Visual Basic 2010 Tutorial

Public Function Main() As Integer

MsgBox(CType(250.48 * 14.05, Single))

Return 0 End Function

End Module

This would produce:

If the first argument is a number or the result of a calculation that produces an integer or afloating-point number, its resulting value must be convertible to an integer or a floating pointnumber up to the range of values of the second argument. Here is an example:

Public Module Exercise

Public Function Main() As Integer

MsgBox(CType(7942.225 * 202.46, UInteger))

Return 0 End Function

End Module

This would produce:

If the first argument is a number or the result of a calculation that produces an integer or afloating-point number, the second argument is a number-based data type but whose rangecannot hold the resulting value of the first argument, the conversion would not be allowed (theconversion will fail):

After the CType() function has performed its conversion, it returns a value that is the samecategory as the second argument. For example, you can call a CType() function that converts anexpression to a long integer. Here is an example:

Public Module Exercise

Public Function Main() As Integer Dim Number As Long

Number = CType(7942.225 * 202.46, Long)

Return 0 End Function

End Module

The function can also return a different type, as long as its type can hold the value produced bythe expression. Here are two examples:

Page 151: Microsoft Visual Basic 2010 Tutorial

Public Module Exercise

Public Function Main() As Integer Dim Number As UInteger

Number = CType(7942.225 * 202.46, Long)

Return 0 End Function

End Module

Or

Public Module Exercise

Public Function Main() As Integer Dim Number As Single

Number = CType(7942.225 * 202.46, Long)

Return 0 End Function

End Module

If you try storing the returned value into a variable that cannot hold it, you would receive anerror:

Home Copyright © 2008-2010 FunctionX, Inc.

Page 152: Microsoft Visual Basic 2010 Tutorial

Visual Basic Built-In Functions: Int/Fix

Description

If you have a decimal number but are interested only in the integral part, to assist you withretrieving that part, the Visual Basic language provides the Int() and the Fix() functions. Theirsyntaxes are:

Public Shared Function Int( _ ByVal Number As { Double | Integer | Long | Object | Short | Single | Decimal }) _ As { Double | Integer | Long | Object | Short | Single | Decimal }Public Shared Function Fix( _ ByVal Number As { Double | Integer | Long | Object | Short | Single | Decimal }) _ As { Double | Integer | Long | Object | Short | Single | Decimal }

Each function must take one argument. The value of the argument must be number-based. Thismeans it can be an integer or a floating-point number. If the value of the argument is integer-based, the function returns the (whole) number. Here is an example

Public Module Exercise

Public Function Main() As Integer Dim Number As Integer

Number = 286345 MsgBox(Int(Number))

Return 0 End Function

End Module

This would produce:

If the value of the argument is a decimal number, the function returns only the integral part. Hereis an example

Public Module Exercise

Public Function Main() As Integer Dim Number As UInteger

Number = 7942.225 * 202.46 MsgBox(Int(Number))

Return 0 End Function

End Module

This would produce:

This function always returns the integral part only, even if you ask it to return a floating-point-based value. Here is an example:

Public Module Exercise

Public Function Main() As Integer Dim Number As Single

Number = 286345.9924 MsgBox(Int(Number))

Return 0

Page 153: Microsoft Visual Basic 2010 Tutorial

End Function

End Module

This would produce:

Home Copyright © 2008-2010 FunctionX, Inc.

Page 154: Microsoft Visual Basic 2010 Tutorial

Visual Basic Built-In Functions: FormatNumber

Introduction

So far, after performing a calculation, we were presenting the result "as is". To appropriatelydisplay a value, the Visual Basic language provides a function named Format. This function canbe used for different types of values The most basic technique consists of passing it anexpression that holds the value to display. The syntax of this function is:

Public Shared Function Format( _ ByVal Expression As Object, _ Optional ByVal Style As String = "" _) As String

As mentioned above, this function can be used in various scenarios. The simplest way to use thisfunction is to pass it a number, a string, or a date/time). The function would then produce thatnumber.

Besides the Format() function, the Visual Basic language provides some additional functions wewill review below.

Formatting a Number

So far, to display a number, we simply passed it to the MsgBox() function or to anotherprocedure. In some cases, you may want the number to display in a particular format. To controlhow the number should display, you can pass the second argument of the Format() function. Thisargument would be passed as a string.

To produce the number in a general format, you can pass the second argument as "g", "G", "f",or "F" .

To display the number with a decimal separator, pass the second argument as "n", "N", or"Standard". Here is an example:

Public Module Exercise

Public Function Main() As Integer Dim Number As Double

Number = 20502.48

MsgBox("Number: " & Format(Number, "STANDARD")) Return 0 End Function

End Module

This would produce:

An alternative to get this format is to call a function named FormatNumber. Its syntax is:

Function FormatNumber( ByVal Expression As Object, Optional ByVal NumDigitsAfterDecimal As Integer = -1, Optional ByVal IncludeLeadingDigit As TriState = TriState.UseDefault, Optional ByVal UseParensForNegativeNumbers As TriState = TriState.UseDefault, Optional ByVal GroupDigits As TriState = TriState.UseDefault) As String

Only the first argument is required and it represents the value to display. If you pass only thisargument, you get the same format as the Format() function called with the Standard option.Here is an example:

Public Module Exercise

Public Function Main() As Integer Dim Number As Double

Number = 20502.48

MsgBox("Number: " & Format(Number, "STANDARD")) MsgBox("Number: " & FormatNumber(Number))

Page 155: Microsoft Visual Basic 2010 Tutorial

Return 0 End Function

End Module

This would produce the same result as above.

If you call the Format() function with the Standard option, it would consider only the number ofdigits on the right side of the decimal separator. If you want to display more digits than thenumber actually has, call the FormatNumber() function and pass a second argument with thedesired number. Here is an example:

Public Module Exercise

Public Function Main() As Integer Dim Number As Double

Number = 20502.48

MsgBox("Number: " & Format(Number, "STANDARD") & vbCrLf & _ "Number: " & FormatNumber(Number, 4)) Return 0 End Function

End Module

This would display:

In the same way, if you want the number to display with less numbers on the right side of thedecimal separator, specify that number.

As a third alternative, you can call the Format() function. In reality, the second argument is usedto format the number with many more options. To represent the integral part of a number, youuse the # sign. To specify the number of digits to display on the right side of the decimalseparator, type a period on the right side of # followed by the number of 0s representing eachdecimal place. Here is an example:

Public Module Exercise

Public Function Main() As Integer Dim Number As Double

Number = 20502.48

MsgBox("Number: " & Format(Number, "#.00000")) Return 0 End Function

End Module

The five 0s on the right side of the period indicate that you want to display 5 digits on the rightside of the period. This would produce:

You can enter as many # signs as you want; it wouldn't change anything. Here is an example:

Public Module Exercise

Public Function Main() As Integer Dim Number As Double

Number = 20502.48

MsgBox("Number: " & Format(Number, "##########.00000")) Return 0 End Function

End Module

This would produce the same result as above. To specify that you want to display the decimalseparator, include its character between the # signs. Here is an example:

Public Module Exercise

Page 156: Microsoft Visual Basic 2010 Tutorial

Public Function Main() As Integer Dim Number As Double

Number = 20502.48

MsgBox("Number: " & Format(Number, "###,#######.00000")) Return 0 End Function

End Module

This would produce:

You can include any other character or symbol you want in the string to be part of the result, butyou should include such a character only at the beginning or the end of the string, otherwise theinterpreter might give you an unexpected result.

Home Copyright © 2008-2010 FunctionX, Inc.

Page 157: Microsoft Visual Basic 2010 Tutorial

Introduction to Visual Basic Built-InFunctions

Overview of Built-In Procedures

Introduction

A procedure is referred to as "built-in" if it shipped with its programming language. To make yourjob a little easier, the Visual Basic language is equipped with many procedures that you can useright away in your program. Based on this, before creating your own procedure, first checkwhether the functionality you are looking for is already implementing in one of the availableprocedures because those that ship with the Visual Basic language are highly reliable and shouldbe preferred.

Before using a built-in procedure, you must of course be familiar with it. This comes either byconsulting the documentation or by experience. This means that you must know its name, itsargument(s), its return value, and its role. The Visual Basic programming language provides one ofthe richest libraries you will ever see. In fact, it is the richest of the .NET-based languages, givingyou access to functions that are not directly available to other languages such as C# or C++/CLI.Because there so many of those functions, we will review only the most usually used. Eventually,when necessary, in other lessons, we may introduce new ones.

Conversion Functions

You may recall that when studying data types, we saw that each had a corresponding functionused to convert a string value or an expression to that type. As a reminder, the general syntax ofthe conversion functions is:

ReturnType = FunctionName(Expression)

The Expression could be of any kind. For example, it could be a string or expression that wouldproduce a value such as the result of a calculation. The conversion function would take such avalue, string, or expression and attempt to convert it. If the conversion is successful, the functionwould return a new value that is of the type specified by the ReturnType in our syntax.

The conversion functions are as follows:

Function

Name Return Type Description

CBool Boolean Converts an expression into a Boolean value

CByte Byte Converts an expression into Byte number

CDbl Double Converts an expression into a floating-point number withdouble precision

CDec Decimal Converts an expression into a decimal number

CInt Integer Converts an expression into an integer (natural) number

CLng Long Converts an expression into a long integer (a largenatural) number

CObj Object Converts an expression into an Object type

CSByte SByte Converts an expression into a signed byte

CShort Short Converts an expression into a short integer

CSng Single Converts an expression into a floating-point number withsingle precision

CUInt UInt Converts an expression into an unsigned integer

CULng ULong Converts an expression into an unsigned long integer

CUShort UShort Converts an expression into an unsigned short integer

These functions allow you to convert a known value to a another type. Besides these functions, theVisual Basic language provides a function named CType. Its syntax is:

CType(expression, typename)

As you can see, the CType() function takes two arguments. The first argument is the expressionor the value that you want to convert. An example could be name of a variable or a calculation:

CType(250.48 * 14.05, ...)

Page 158: Microsoft Visual Basic 2010 Tutorial

The second argument is the type of value you want to convert the first argument to. From whathave learned so far, this second argument can be one of the data types we reviewed in Lesson 3.Here is an example:

CType(250.48 * 14.05, Single)

If you choose one of the Visual Basic language's data types, the expression produced by the firstargument must be able to produce a value that is conform to the type of the second argument:

The conversion from the first argument to the type of the second argument must be possible:the value produced by the first must be convertible to the second arguments. For example, ifthe first argument is a calculation, the second argument must be a number-based data type.In the same way, you cannot convert a date to a number-based type

If the first argument is a number or the result of a calculation, its resulting value must belower than or up to the range of values of the second argument. Here is an example:

Public Module Exercise

Public Function Main() As Integer

MsgBox(CType(250.48 * 14.05, Single))

Return 0 End Function

End Module

This would produce:

If the first argument is a number or the result of a calculation that produces an integer or afloating-point number, its resulting value must be convertible to an integer or a floating pointnumber up to the range of values of the second argument. Here is an example:

Public Module Exercise

Public Function Main() As Integer

MsgBox(CType(7942.225 * 202.46, UInteger))

Return 0 End Function

End Module

This would produce:

If the first argument is a number or the result of a calculation that produces an integer or afloating-point number, the second argument is a number-based data type but whose rangecannot hold the resulting value of the first argument, the conversion would not be allowed (theconversion will fail):

Page 159: Microsoft Visual Basic 2010 Tutorial

After the CType() function has performed its conversion, it returns a value that is the samecategory as the second argument. For example, you can call a CType() function that converts anexpression to a long integer. Here is an example:

Public Module Exercise

Public Function Main() As Integer Dim Number As Long

Number = CType(7942.225 * 202.46, Long)

Return 0 End Function

End Module

The function can also return a different type, as long as its type can hold the value produced bythe expression. Here are two examples:

Public Module Exercise

Public Function Main() As Integer Dim Number As UInteger

Number = CType(7942.225 * 202.46, Long)

Return 0 End Function

End Module

Or

Public Module Exercise

Public Function Main() As Integer Dim Number As Single

Number = CType(7942.225 * 202.46, Long)

Return 0 End Function

End Module

If you try storing the returned value into a variable that cannot hold it, you would receive anerror:

Home Copyright © 2008-2010 FunctionX, Inc.

Page 160: Microsoft Visual Basic 2010 Tutorial

Built-In Functions: Format Percent

Introduction

To appropriately display a value, the Visual Basic language provides a function named Format.This function can be used for different types of values The most basic technique consists ofpassing it an expression that holds the value to display. The syntax of this function is:

Public Shared Function Format( _ ByVal Expression As Object, _ Optional ByVal Style As String = "" _) As String

As mentioned above, this function can be used in various scenarios. The simplest way to use thisfunction is to pass it a number, a string, or a date/time). The function would then produce thatnumber.

Besides the Format() function, the Visual Basic language provides some additional functions wewill review below.

Formatting a Percentage Value

A percentage of a number represents its rate on a scale, usually of 100 (or more). The number isexpressed using digits accompanied by the % sign. Besides the Format() function, to supportpercent values, the Visual Basic language provides a function named FormatPercent. Its syntaxis:

Function FormatPercent( ByVal Expression As Object, Optional ByVal NumDigitsAfterDecimal As Integer = -1, Optional ByVal IncludeLeadingDigit As TriState = TriState.UseDefault, Optional ByVal UseParensForNegativeNumbers As TriState = TriState.UseDefault, Optional ByVal GroupDigits As TriState = TriState.UseDefault) As String

Only the first argument is required and it is the number that needs to be formatted. When callingthis function, pay attention to the number you provide as argument. If the number represents apercentage value as a fraction of 0 to 1, make sure you provide it as such. An example would be0.25. In this case, the Visual Basic interpreter would multiply the value by 100 to give the result.Here is an example:

Public Module Exercise

Public Function Main() As Integer Dim DiscountRate As Double

DiscountRate = 0.25

MsgBox("Discount Rate: " & FormatPercent(DiscountRate)) Return 0 End Function

End Module

This would produce:

On the other hand, if you pass the value in the hundreds, the interpreter would still multiply it by100. Although it is not impossible to get a percentage value in the hundreds or thousands, youshould make sure that's the type of value you mean to get.

Besides the FormatPercent() function, to format a number to its percentage equivalent, you cancall the Format() function and pass the second argument as "Percent", "p", or "P". Here is anexample:

Public Module Exercise

Public Function Main() As Integer Dim DiscountRate As Double

DiscountRate = 0.25

MsgBox("Discount Rate: " & Format(DiscountRate, "Percent")) Return 0

Page 161: Microsoft Visual Basic 2010 Tutorial

End Function

End Module

Home Copyright © 2008-2010 FunctionX, Inc.

Page 162: Microsoft Visual Basic 2010 Tutorial

Visual Basic Built-In Functions: Len

The Memory Used by a Data Type

We know that different data types are used to store different values. To do that, each data typerequires a different amount of space in the computer memory. To know the amount of space thata data type or a variable needs, you can call the Len() function.

Its syntax is:

Public Shared Function Len( _ ByVal Expression As { Boolean | Byte | SByte | Char | Double | Integer | UInteger | Long | ULong | Object | Short | UShort | Single | String | DateTime | Decimal } _) As Integer

To call this function, you can declare a variable with a data type of your choice and optionallyinitialize with the appropriate value, then pass that variable to the function. Here is an example:

Public Module Exercise

Public Function Main() As Integer Dim Value As Integer

Value = 774554

MsgBox(Value & " needs " & Len(Value) & " bytes to be stored in memory.") Return 0 End Function

End Module

This would produce:

Home Copyright © 2008-2010 FunctionX, Inc.

Page 163: Microsoft Visual Basic 2010 Tutorial

Visual Basic Built-In Functions: RandomFunctions

Description

A random number is a value that is not known in advanced until it is generated by the compiler.To assist you with getting a random number, the Visual Basic language provides a functionnamed Rnd. Its syntax is:

Public Shared Function Rnd[(Number)] As Single

This function takes an optional argument. If the argument is not passed, the compiler wouldsimply generate a positive decimal number between 0 and 1. Here is an example:

Public Module Exercise

Public Function Main() As Integer MsgBox("Random Number: " & Rnd())

Return 0 End Function

End Module

This would produce:

You may wonder how the compiler generates a random number. Without going into all the details,in most cases, a compiler refers to the system clock (the clock of the computer on which theapplication is). It uses a certain algorithm to get that number.

If you call the function like we did above, every time you execute the application, you are likely toget the same result. Depending on how you want to use the number, in some cases, you maywant to get a different number every time. To support this, random arithmetic supports what isreferred to as a seed. If you do not use a seed, the compiler would keep the same number itgenerated from the system clock the first time it was asked to produce a random number. Seedingallows the compiler to reset this mechanism, which would result in a new random number.

To assist you with seeding, the Visual Basic language provides a function named Randomize. Itssyntax is:

Public Shared Sub Randomize ([ Number ])

This function takes one optional argument. If you can this function without the argument, thecompiler would refer to the system clock to generate the new random number. Of course, to getthe number, you must call this function before calling Rnd(). Here is an example:

Public Module Exercise

Public Function Main() As Integer Randomize()

MsgBox("Random Number: " & Rnd())

Return 0 End Function

End Module

This time, every time the Rnd() function is called, the compiler generates a new number. Insteadof letting the compiler refer to the system clock, you can provide your own seed value. To do this,pass a number to the Randomize() function.

We mentioned that the Rnd() function generates a number between 0 and 1. Of course, in somecases you will want the number to be in a higher range, such as between 0 and 100 or between 0and 100000. All you have to do is to multiply the result to a number of your choice. Here is anexample:

Public Module Exercise

Public Function Main() As Integer Randomize()

Page 164: Microsoft Visual Basic 2010 Tutorial

MsgBox("Random Number: " & CStr(100 * Rnd()))

Return 0 End Function

End Module

This would produce:

Also notice that the result is a decimal number. If you interested in only the integral part of thenumber, you can call the Int() function.

Besides Visual Basic's own combination of the Rnd() and the Randomize() functions, the.NET Framework supports random numbers in another way (using Random).

Home Copyright © 2008-2010 FunctionX, Inc.

Page 165: Microsoft Visual Basic 2010 Tutorial

Boolean Values

Fundamentals of Boolean Values

The Boolean Data Type

A value is referred to as Boolean if it can be either true or false. Like a number or a string, aBoolean value can be stored in a variable. To declare such a variable, use the Boolean keyword.Here is an example:

Public Module Exercise

Public Function Main() As Integer Dim EmployeeIsMarried As Boolean

Return 0 End Function

End Module

To actually use a Boolean variable, you can assign a value to it. By default, if you declare aBoolean variable but do not initialized it, it receives a value of False:

Public Module Exercise

Public Function Main() As Integer Dim EmployeeIsMarried As Boolean

MsgBox("Employee Is Married? " & EmployeeIsMarried) Return 0 End Function

End Module

This would produce:

To initialize a Boolean variable, assign it a True or a False value. In the Visual Basic language, aBoolean variable can also deal with numeric values. The False value is equivalent to 0. Forexample, instead of False, you can initialize a Boolean variable with 0. Any other numeric value,whether positive or negative, corresponds to True:

Public Module Exercise

Public Function Main() As Integer Dim EmployeeIsMarried As Boolean

EmployeeIsMarried = -792730 MsgBox("Employee Is Married? " & EmployeeIsMarried) Return 0 End Function

End Module

The number can be decimal or hexadecimal:

Public Module Exercise

Public Function Main() As Integer Dim EmployeeIsMarried As Boolean

EmployeeIsMarried = &HFA26B5 MsgBox("Employee Is Married? " & EmployeeIsMarried) Return 0 End Function

End Module

Passing a Boolean Variable as Argument

As done with the other data types we have used so far, a Boolean values can be involved with aprocedure. This means that a Boolean variable can be passed to a procedure and/or a function canbe made to return a Boolean value.

To pass an argument as a Boolean value, in the parentheses of the procedure, type the name of

Page 166: Microsoft Visual Basic 2010 Tutorial

the argument followed by the As Boolean expression. Here is an example:

Private Sub CheckingEmployee(ByVal IsFullTime As Boolean)

End Sub

In the same way, you can pass as many Boolean arguments as you need, and you can combineBoolean and non-Boolean arguments as you judge necessary. Then, in the body of the procedure,use (or don't use) the Boolean argument.

Returning a Boolean Value

Just as done for the other data types, you can create a function that returns a Boolean value.When declaring the function, specify its name and the As Boolean expression on the right side ofthe closing parenthesis. Here is an example:

Public Function IsDifferent() As Boolean End Function

Of course, the function can take arguments of any kind you judge necessary:

Public Function IsDifferent(ByVal Value1 As Integer, ByVal Value2 As Integer) As Boolean End Function

In the body of the function, do whatever you judge necessary. Before exiting the function, youmust return a value that evaluates to True or False.

Home Copyright © 2008-2010 FunctionX, Inc.

Page 167: Microsoft Visual Basic 2010 Tutorial

Logical Operators

Introduction

A comparison is an operation used to get the Boolean result of two values one checked againstthe other. Such a comparison is performed between two values of the same type.

Equality

To compare two variables for equality, use the = operator. Its syntax is:

Value1 = Value2

The equality operation is used to find out whether two variables (or one variable and a constant)hold the same value. From our syntax, the value of Value1 would be compared with the value ofValue2. If Value1 and Value2 hold the same value, the comparison produces a True result. If theyare different, the comparison renders false or 0.

Here is an example:

Module Exercise

Public Function Main() As Integer Dim IsFullTime As Boolean

MsgBox("Is Employee Full Time? " & IsFullTime)

IsFullTime = True MsgBox("Is Employee Full Time? " & IsFullTime) Return 0 End Function

End Module

This would produce:

Inequality <>

As opposed to checking for equality, you may instead want to know whether two values aredifferent. The operator used to perform this comparison is <> and its formula is:

Variable1 <> Variable2

Page 168: Microsoft Visual Basic 2010 Tutorial

If the operands on both sides of the operator are the same, the comparison renders false. If bothoperands hold different values, then the comparison produces a true result. This also shows thatthe equality = and the inequality <> operators are opposite.

Here is an example:

Module Exercise

Public Function IsDifferent(ByVal Value1 As Integer, ByVal Value2 As Integer) As Boolean Return (Value1 <> Value2) End Function

Public Function Main() As Integer Dim a%, b% Dim Result As Boolean

a% = 12 : b% = 48 Result = IsDifferent(a%, b%)

MsgBox("The resulting comparison of 12 <> 48 is " & Result) Return 0 End Function

End Module

This would produce:

A Lower Value <

To find out whether one value is lower than another, use the < operator. Its syntax is:

Value1 < Value2

The value held by Value1 is compared to that of Value2. As it would be done with otheroperations, the comparison can be made between two variables, as in Variable1 < Variable2. If thevalue held by Variable1 is lower than that of Variable2, the comparison produces a True.

Here is an example:

Module Exercise

Page 169: Microsoft Visual Basic 2010 Tutorial

Public Function Main() As Integer Dim PartTimeSalary, ContractorSalary As Double Dim IsLower As Boolean

PartTimeSalary = 20.15 ContractorSalary = 22.48 IsLower = PartTimeSalary < ContractorSalary

MsgBox("Part Time Salary: " & PartTimeSalary & vbCrLf & "Contractor Salary: " & ContractorSalary & vbCrLf & "Is PartTimeSalary < ContractorSalary? " & IsLower)

PartTimeSalary = 25.55 ContractorSalary = 12.68 IsLower = PartTimeSalary < ContractorSalary

MsgBox("Part Time Salary: " & PartTimeSalary & vbCrLf & "Contractor Salary: " & ContractorSalary & vbCrLf & "Is PartTimeSalary < ContractorSalary? " & IsLower) Return 0 End Function

End Module

This would produce:

Equality and Lower Value <=

The previous two operations can be combined to compare two values. This allows you to know iftwo values are the same or if the first is less than the second. The operator used is <= and itssyntax is:

Value1 <= Value2

The <= operation performs a comparison as any of the last two. If both Value1 and VBalue2 holdthe same value, result is true or positive. If the left operand, in this case Value1, holds a valuelower than the second operand, in this case Value2, the result is still true:

Greater Value >

When two values of the same type are distinct, one of them is usually higher than the other.VBasic provides a logical operator that allows you to find out if one of two values is greater thanthe other. The operator used for this operation uses the > symbol. Its syntax is:

Value1 > Value2

Both operands, in this case Value1 and Value2, can be variables or the left operand can be avariable while the right operand is a constant. If the value on the left of the > operator is greaterthan the value on the right side or a constant, the comparison produces a True value. Otherwise,the comparison renders False or null:

Page 170: Microsoft Visual Basic 2010 Tutorial

Here is an example:

Module Exercise

Public Function Main() As Integer Dim PartTimeSalary, ContractorSalary As Double Dim IsLower As Boolean

PartTimeSalary = 20.15 ContractorSalary = 22.48 IsLower = PartTimeSalary > ContractorSalary

MsgBox("Part Time Salary: " & PartTimeSalary & vbCrLf & "Contractor Salary: " & ContractorSalary & vbCrLf & "Is PartTimeSalary > ContractorSalary? " & IsLower)

PartTimeSalary = 25.55 ContractorSalary = 12.68 IsLower = PartTimeSalary > ContractorSalary

MsgBox("Part Time Salary: " & PartTimeSalary & vbCrLf & "Contractor Salary: " & ContractorSalary & vbCrLf & "Is PartTimeSalary > ContractorSalary? " & IsLower) Return 0 End Function

End Module

This would produce:

Greater or Equal Value >=

The greater than or the equality operators can be combined to produce an operator as follows:>=. This is the "greater than or equal to" operator. Its syntax is:

Value1 >= Value2

A comparison is performed on both operands: Value1 and Value2. If the value of Value1 and thatof Value2 are the same, the comparison produces a True value. If the value of the left operand isgreater than that of the right operand, the comparison still produces True. If the value of the leftoperand is strictly less than the value of the right operand, the comparison produces a Falseresult:

Page 171: Microsoft Visual Basic 2010 Tutorial

Home Copyright © 2010 FunctionX, Inc.

Page 172: Microsoft Visual Basic 2010 Tutorial

Introduction to Conditional Statements

Checking Whether a Condition is True/False

Introduction

In some programming assignments, you must find out whether a given situation bears a validvalue. This is done by checking a condition. To support this, the Visual Basic language provides aseries of words that can be combined to perform this checking. Checking a condition usuallyproduces a True or a False result.

Once the condition has been checked, you can use the result (as True or False) to take action.Because there are different ways to check a condition, there are also different types of keywordsto check different things. To use them, you must be aware of what each does or cannot do so youwould select the right one.

Practical Learning: Introducing Conditional Statements

1. Start Microsoft Visual Basic and create a Console Application named BCR1

2. In the Solution Explorer, right-click Module1.vb and click Rename

3. Type BethesdaCarRental.vb and press Enter

4. Accept to change the file name and change the document as follows:

5. To execute the exercise, press Ctrl + F5

6. Enter the Employee name as Helene Mukoko, the hourly salary as 22.35, and the weeklyhours as 38

Module BethesdaCarRental

Public Function Main() As Integer Dim EmployeeName As String Dim StrHourlySalary As String, StrWeeklyHours As String Dim HourlySalaryFormatter As String Dim WeeklyHoursFormatter As String Dim Payroll As String

HourlySalaryFormatter = "0.00" WeeklyHoursFormatter = "0.00"

EmployeeName = InputBox("Enter Employee Name:", "Bethesda Car Rental", "John Doe") StrHourlySalary = InputBox("Enter Employee Hourly Salary:", "Bethesda Car Rental", "0.00")

HourlySalaryFormatter = FormatCurrency(CDbl(StrHourlySalary))

StrWeeklyHours = InputBox("Enter Employee Weekly Hours:", "Bethesda Car Rental", "0.00")

WeeklyHoursFormatter = FormatNumber(CDbl(StrWeeklyHours))

Payroll = "======================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Employee Payroll =-=-==" & vbCrLf & "-------------------------------------------" & vbCrLf & "Employee Name:" & vbTab & EmployeeName & vbCrLf & "Hourly Salary:" & vbTab & HourlySalaryFormatter & vbCrLf & "Weekly Hours:" & vbTab & WeeklyHoursFormatter & vbCrLf & "======================"

MsgBox(Payroll, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") Return 0 End Function

End Module

Page 173: Microsoft Visual Basic 2010 Tutorial

7. Close the message box and the DOS window to return to your programming environment

If a Condition is True/False, Then What?

The If...Then statement examines the truthfulness of an expression. Structurally, its formula is:

If ConditionToCheck Then Statement

Therefore, the program examines a condition, in this case ConditionToCheck. ThisConditionToCheck can be a simple expression or a combination of expressions. If theConditionToCheck is true, then the program will execute the Statement.

There are two ways you can use the If...Then statement. If the conditional formula is shortenough, you can write it on one line, like this:

If ConditionToCheck Then Statement

Here is an example:

Module Exercise

Public Function Main() As Integer Dim IsMarried As Boolean Dim TaxRate As Double

TaxRate = 33.0

MsgBox("Tax Rate: " & TaxRate & "%")

IsMarried = True

If IsMarried = True Then TaxRate = 30.65

MsgBox("Tax Rate: " & TaxRate & "%") Return 0 End Function

End Module

This would produce:

Page 174: Microsoft Visual Basic 2010 Tutorial

If there are many statements to execute as a truthful result of the condition, you should write thestatements on alternate lines. Of course, you can use this technique even if the condition you areexamining is short. In this case, one very important rule to keep is to terminate the conditionalstatement with End If. The formula used is:

If ConditionToCheck Then StatementEnd If

Here is an example:

Module Exercise

Public Function Main() As Integer Dim IsMarried As Boolean Dim TaxRate As Double

TaxRate = 33.0

MsgBox("Tax Rate: " & TaxRate & "%")

IsMarried = True If IsMarried = True Then TaxRate = 30.65

MsgBox("Tax Rate: " & TaxRate & "%") End If

Return 0 End Function

End Module

Practical Learning: Using If...Then

1. To use an If condition, change the document as follows:

2. Execute the application

3. Enter the Employee name as Helene Mukoko, the hourly salary as 2W.o5, and the weeklyhours as Thirty Eight

Module BethesdaCarRental

Public Function Main() As Integer Dim EmployeeName As String Dim StrHourlySalary As String, StrWeeklyHours As String Dim HourlySalaryFormatter As String Dim WeeklyHoursFormatter As String Dim Payroll As String

HourlySalaryFormatter = "0.00" WeeklyHoursFormatter = "0.00"

EmployeeName = InputBox("Enter Employee Name:", "Bethesda Car Rental", "John Doe") StrHourlySalary = InputBox("Enter Employee Hourly Salary:", "Bethesda Car Rental", "0.00")

If IsNumeric(StrHourlySalary) = True Then HourlySalaryFormatter = FormatCurrency(CDbl(StrHourlySalary)) End If

StrWeeklyHours = InputBox("Enter Employee Weekly Hours:", "Bethesda Car Rental", "0.00")

If IsNumeric(StrWeeklyHours) = True Then WeeklyHoursFormatter = FormatNumber(CDbl(StrWeeklyHours)) End If

Payroll = "======================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Employee Payroll =-=-==" & vbCrLf & "-------------------------------------------" & vbCrLf & "Employee Name:" & vbTab & EmployeeName & vbCrLf & "Hourly Salary:" & vbTab & HourlySalaryFormatter & vbCrLf & "Weekly Hours:" & vbTab & WeeklyHoursFormatter & vbCrLf & "======================"

MsgBox(Payroll, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") Return 0 End Function

End Module

Page 175: Microsoft Visual Basic 2010 Tutorial

4. Close the message box and the DOS window then return to your programming environment

Using the Default Value of a Boolean Expression

In the previous lesson, we saw that when you declare a Boolean variable, by default, it isinitialized with the False value. Here is an example:

Module Exercise

Public Function Main() As Integer Dim IsMarried As Boolean

MsgBox("Employee Is Married? " & IsMarried) Return 0 End Function

End Module

This would produce:

Based on this, if you want to check whether a newly declared and uninitialized Boolean variable isfalse, you can omit the = False expression applied to it. Here is an example:

Module Exercise

Public Function Main() As Integer Dim IsMarried As Boolean Dim TaxRate As Double

TaxRate = 33.0

If IsMarried Then TaxRate = 30.65

MsgBox("Tax Rate: " & TaxRate & "%")

Return 0 End Function

End Module

This would produce:

Notice that there is no = after the If IsMarried expression. In this case, the compiler assumes thatthe value of the variable is False. On the other hand, if you want to check whether the variable isTrue, make sure you include the = True expression. Overall, whenever in doubt, it is safer toalways initialize your variable and it is safer to include the = True or = False expression whenevaluating the variable:

Module Exercise

Public Function Main() As Integer Dim IsMarried As Boolean Dim TaxRate As Double

TaxRate = 36.45 ' %

IsMarried = True

Page 176: Microsoft Visual Basic 2010 Tutorial

If IsMarried = False Then TaxRate = 33.15

MsgBox("Tax Rate: " & TaxRate & "%")

Return 0 End Function

End Module

In the previous lesson, we introduced some Boolean-based functions such IsNumeric and IsDate.The default value of these functions is true. This means that when you call them, you can omit the= True expression.

Practical Learning: Using the Default Value of Boolean-BasedFunctions

1. To use the default value of the IsNumeric function, change the document as follows:

Module BethesdaCarRental

Public Function Main() As Integer . . . No Change

If IsNumeric(StrHourlySalary) Then HourlySalaryFormatter = FormatCurrency(CDbl(StrHourlySalary)) End If

. . . No Change

If IsNumeric(StrWeeklyHours) Then WeeklyHoursFormatter = FormatNumber(CDbl(StrWeeklyHours)) End If

. . . No Change Return 0 End Function

End Module

2. Save the file

If-Condition Based Functions

Choosing a Value

We have learned how to check whether a condition is True or False and take an action. Here is anexample:

Module Exercise

Public Function Main() As Integer Dim Status As UShort, EmploymentStatus As String

Status = 1 EmploymentStatus = "Unknown"

If Status = 1 Then EmploymentStatus = "Full Time" End If

MsgBox("Employment Status: " & EmploymentStatus)

Return 0 End Function

End Module

To provide an alternative to this operation, the Visual Basic language provides a function namedChoose. Its syntax is:

Public Function Choose( _ ByVal Index As Double, _ ByVal ParamArray Choice() As Object _) As Object

This function takes two required arguments. The fist argument is equivalent to theConditionToCheck of our If...Then formula. For the Choose() function, this first argument must bea number (a Byte, an SByte, a Short, a UShort, an Integer, a UInteger, a Long, a ULong, aSingle, a Double, or a Decimal value). This is the value against which the second argument willbe compared. Before calling the function, you must know the value of the first argument. To takecare of this, you can first declare a variable and initialize it with the desired value. Here is anexample:

Module Exercise

Public Function Main() As Integer Dim Status As UShort

Status = 1

Page 177: Microsoft Visual Basic 2010 Tutorial

Choose(Status, ...)

Return 0 End Function

End Module

The second argument can be the Statement of our formula. Here is an example:

Choose(Status, "Full Time")

We will see in the next sections that the second argument is actually a list of values and eachvalue has a specific position referred to as its index. To use the function in an If...Then scenario,you pass only one value as the second argument. This value/argument has an index of 1. Whenthe Choose() function is called in an If...Then implementation, if the first argument holds a valueof 1, the second argument is validated.

When the Choose() function has been called, it returns a value of type Object. You can retrievethat value, store it in a variable and use it as you see fit. Here is an example:

Module Exercise

Public Function Main() As Integer Dim Status As UShort, EmploymentStatus As String

Status = 1

EmploymentStatus = Choose(Status, "Full Time")

MsgBox("Employment Status: " & EmploymentStatus)

Return 0 End Function

End Module

This would produce:

Switching to a Value

To give you another alternative to an If...Then condition, the Visual Basic language provides afunction named Switch. Its syntax is:

Public Function Switch( _ ByVal ParamArray VarExpr() As Object _) As Object

In the .NET Framework, there is another Switch implement that can cause a conflict whenyou call the Switch() function in your program. Therefore, you must qualify this functionwhen calling it. To do this, use Microsoft.VisualBasic.Switch.

This function takes one required argument. To use it in an If...Then scenario, pass the argumentas follows:

Switch(ConditionToCheck, Statement)

In the ConditionToCheck placeholder, pass a Boolean expression that can be evaluated to True orFalse. If that condition is true, the second argument would be executed.

When the Switch() function has been called, it produces a value of type Object (such as a string)that you can use as you see fit. For example, you can store it in a variable. Here is an example:

Module Exercise

Public Function Main() As Integer Dim Status As UShort, EmploymentStatus As String

Status = 2 EmploymentStatus = "Unknown"

EmploymentStatus = Microsoft.VisualBasic.Switch(Status = 1, "Full Time")

MsgBox("Employment Status: " & EmploymentStatus)

Return 0 End Function

End Module

In this example, we used a number as argument. You can also use another type of value, such asan enumeration. Here is an example:

Page 178: Microsoft Visual Basic 2010 Tutorial

Module Exercise Private Enum EmploymentStatus FullTime PartTime Contractor Seasonal Unknown End Enum

Public Function Main() As Integer Dim Status As EmploymentStatus Dim Result As String

Status = EmploymentStatus.FullTime Result = "Unknown"

Result = Microsoft.VisualBasic.Switch( _ Status = EmploymentStatus.FullTime, "Full Time")

MsgBox("Employment Status: " & Result)

Return 0 End Function

End Module

What Else When a Condition is True/False?

The If...Then...Else Condition

The If...Then statement offers only one alternative: to act if the condition is true. Whenever youwould like to apply an alternate expression in case the condition is false, you can use theIf...Then...Else statement. The formula of this statement is:

If ConditionToCheck Then Statement1Else Statement2End If

When this section of code is executed, if the ConditionToCheck is true, then the first statement,Statement1, is executed. If the ConditionToCheck is false, the second statement, in this caseStatement2, is executed.

Here is an example:

Module Exercise

Public Function Main() As Integer Dim MemberAge As Int16 Dim MemberCategory As String

MemberAge = 16

If MemberAge <= 18 Then MemberCategory = "Teen" Else MemberCategory = "Adult" End If

MsgBox("Membership: " & MemberCategory)

Return 0 End Function

End Module

This would produce:

Practical Learning: Using If...Then...Else

1. To use the Else clause, make the following changes to the file:

Module BethesdaCarRental

Public Function Main() As Integer Dim EmployeeName As String Dim StrHourlySalary As String, StrWeeklyHours As String Dim HourlySalaryFormatter As String Dim WeeklyHoursFormatter As String Dim Payroll As String

Page 179: Microsoft Visual Basic 2010 Tutorial

2. Execute the application

3. Enter the Employee name as Helene Mukoko, the hourly salary as 2W.o5, and the weeklyhours as Thirty Eight

4. Close the message box and the DOS window then return to your programming environment

5. To calculate the employee's pay, change the document as follows:

HourlySalaryFormatter = "0.00" WeeklyHoursFormatter = "0.00"

EmployeeName = InputBox("Enter Employee Name:", "Bethesda Car Rental", "John Doe") StrHourlySalary = InputBox("Enter Employee Hourly Salary:", "Bethesda Car Rental", "0.00")

If IsNumeric(StrHourlySalary) Then HourlySalaryFormatter = FormatCurrency(CDbl(StrHourlySalary)) Else MsgBox("The number " & StrHourlySalary & " you entered " & "for the hourly salary is not valid", MsgBoxStyle.Exclamation Or MsgBoxStyle.Critical, "Bethesda Car Rental") End If

StrWeeklyHours = InputBox("Enter Employee Weekly Hours:", "Bethesda Car Rental", "0.00")

If IsNumeric(StrWeeklyHours) Then WeeklyHoursFormatter = FormatNumber(CDbl(StrWeeklyHours)) Else MsgBox("The value " & StrWeeklyHours & " you provided " & "for the weekly hours is not valid", MsgBoxStyle.Exclamation Or MsgBoxStyle.Critical, "Bethesda Car Rental") End If

Payroll = "======================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Employee Payroll =-=-==" & vbCrLf & "-------------------------------------------" & vbCrLf & "Employee Name:" & vbTab & EmployeeName & vbCrLf & "Hourly Salary:" & vbTab & HourlySalaryFormatter & vbCrLf & "Weekly Hours:" & vbTab & WeeklyHoursFormatter & vbCrLf & "======================"

MsgBox(Payroll, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") Return 0 End Function

End Module

Module BethesdaCarRental

Public Function Main() As Integer Dim EmployeeName As String Dim StrHourlySalary As String, StrWeeklyHours As String Dim HourlySalary As Double Dim WeeklyHours As Double Dim RegularTime As Double, Overtime As Double Dim RegularPay As Double, OvertimePay As Double Dim NetPay As Double

Dim Payroll As String

HourlySalary = "0.00" WeeklyHours = "0.00"

EmployeeName = InputBox("Enter Employee Name:", "Bethesda Car Rental", "John Doe") StrHourlySalary = InputBox("Enter Employee Hourly Salary:", "Bethesda Car Rental", "0.00")

If IsNumeric(StrHourlySalary) Then HourlySalary = CDbl(StrHourlySalary) Else MsgBox("The number " & StrHourlySalary & " you entered " & "for the hourly salary is not valid", MsgBoxStyle.Exclamation Or MsgBoxStyle.Critical, "Bethesda Car Rental") End If

StrWeeklyHours = InputBox("Enter Employee Weekly Hours:", "Bethesda Car Rental", "0.00")

If IsNumeric(StrWeeklyHours) Then WeeklyHours = CDbl(StrWeeklyHours) Else MsgBox("The value " & StrWeeklyHours & " you provided " & "for the weekly hours is not valid", MsgBoxStyle.Exclamation Or MsgBoxStyle.Critical, "Bethesda Car Rental") End If

If WeeklyHours < 40 Then RegularTime = WeeklyHours

Page 180: Microsoft Visual Basic 2010 Tutorial

6. Execute the application

7. Enter the Employee name as Helene Mukoko, the hourly salary as 22.35, and the weeklyhours as 42.50

8. Close the message box and the DOS window then return to your programming environment

If...Then...Else-Condition Based Functions

Immediate If

To assist you with checking a condition and its alternative, the Visual Basic language provides afunction named IIf. Its syntax is:

Public Function IIf( _ ByVal Expression As Boolean, _ ByVal TruePart As Object, _ ByVal FalsePart As Object _ ) As Object

This function operates like an If...Then...Else condition. It takes three required arguments andreturns a result of type Object. This returned value will hold the result of the function.

The condition to check is passed as the first argument:

If that condition is true, the function returns the value of the TruePart argument and the lastargument is ignored

If the condition is false, the first argument is ignored and the function returns the value of thesecond argument

As mentioned already, you can retrieved the value of the right argument and assign it to the resultof the function. The expression we saw early can be written as follows:

Module Exercise

Public Function Main() As Integer

Overtime = 0 RegularPay = HourlySalary * RegularTime OvertimePay = 0 NetPay = RegularPay Else RegularTime = 40 Overtime = WeeklyHours - 40 RegularPay = HourlySalary * 40 OvertimePay = HourlySalary * Overtime NetPay = RegularPay + OvertimePay End If

Payroll = "======================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Employee Payroll =-=-==" & vbCrLf & "-------------------------------------------" & vbCrLf & "Employee Name:" & vbTab & EmployeeName & vbCrLf & "Hourly Salary:" & vbTab & FormatCurrency(HourlySalary) & vbCrLf & "Weekly Hours:" & vbTab & FormatNumber(WeeklyHours) & vbCrLf & "Regular Pay:" & vbTab & FormatCurrency(RegularPay) & vbCrLf & "Overtime Pay:" & vbTab & FormatCurrency(OvertimePay) & vbCrLf & "Total Pay:" & vbTab & FormatCurrency(NetPay) & vbCrLf & "======================"

MsgBox(Payroll, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") Return 0 End Function

End Module

Page 181: Microsoft Visual Basic 2010 Tutorial

Dim MemberAge As Int16 Dim MemberCategory As String

MemberAge = 16

MemberCategory = IIf(MemberAge <= 18, "Teen", "Adult")

MsgBox("Membership: " & MemberCategory)

Return 0 End Function

End Module

This would produce the same result we saw earlier.

Practical Learning: Using the Immediate If Function

1. To use the IIf() function, change the document as follows:

Module BethesdaCarRental

Public Function Main() As Integer Dim EmployeeName As String Dim Gender As Byte Dim StrGender As String Dim StrHourlySalary As String, StrWeeklyHours As String Dim HourlySalary As Double Dim WeeklyHours As Double Dim RegularTime As Double, Overtime As Double Dim RegularPay As Double, OvertimePay As Double Dim NetPay As Double

Dim Payroll As String

HourlySalary = "0.00" WeeklyHours = "0.00"

EmployeeName = InputBox("Enter Employee Name:", _ "Bethesda Car Rental", _ "John Doe")

Gender = InputBox("Enter Employee Gender (1=Female/2=Male):", "Bethesda Car Rental", "1") StrGender = IIf(Gender = 1, "Female", "Male")

StrHourlySalary = InputBox("Enter Employee Hourly Salary:", "Bethesda Car Rental", "0.00")

If IsNumeric(StrHourlySalary) Then HourlySalary = CDbl(StrHourlySalary) Else MsgBox("The number " & StrHourlySalary & " you entered " & "for the hourly salary is not valid", MsgBoxStyle.Exclamation Or MsgBoxStyle.Critical, "Bethesda Car Rental") End If

StrWeeklyHours = InputBox("Enter Employee Weekly Hours:", "Bethesda Car Rental", "0.00")

If IsNumeric(StrWeeklyHours) Then WeeklyHours = CDbl(StrWeeklyHours) Else MsgBox("The value " & StrWeeklyHours & " you provided " & "for the weekly hours is not valid", MsgBoxStyle.Exclamation Or MsgBoxStyle.Critical, "Bethesda Car Rental") End If

If WeeklyHours < 40 Then RegularTime = WeeklyHours Overtime = 0 RegularPay = HourlySalary * RegularTime OvertimePay = 0 NetPay = RegularPay Else RegularTime = 40 Overtime = WeeklyHours - 40 RegularPay = HourlySalary * 40 OvertimePay = HourlySalary * Overtime NetPay = RegularPay + OvertimePay End If

Payroll = "======================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Employee Payroll =-=-==" & vbCrLf & "-------------------------------------------" & vbCrLf & "Employee Name:" & vbTab & EmployeeName & vbCrLf & "Employee Gender:" & vbTab & StrGender & vbCrLf & "Hourly Salary:" & vbTab & FormatCurrency(HourlySalary) & vbCrLf & "Weekly Hours:" & vbTab & FormatNumber(WeeklyHours) & vbCrLf & "Regular Pay:" & vbTab & FormatCurrency(RegularPay) & vbCrLf & "Overtime Pay:" & vbTab & FormatCurrency(OvertimePay) & vbCrLf & "Total Pay:" & vbTab & FormatCurrency(NetPay) & vbCrLf & "======================"

Page 182: Microsoft Visual Basic 2010 Tutorial

2. Execute the application

3. Enter the Employee name as Raymond Kouma, the gender as 2, hourly salary as 28.25, andthe weekly hours as 44.50

4. Close the message box and the DOS window then return to your programming environment

5. Create a new Console Application named BCR2

6. In the Solution Explorer, right-click Module1.vb and click Rename

7. Type BethesdaCarRental.vb and press Enter

8. Accept to change the file name and change the document as follows:

9. Execute the application

10. Enter the customer name as James Wiley, the start date as 11/07/2008, the end date as11/10/2008, and the rate applied 49.95

MsgBox(Payroll, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") Return 0 End Function

End Module

Module BethesdaCarRental

Public Function Main() As Integer Dim CustomerName As String Dim RentStartDate As Date, RentEndDate As Date Dim NumberOfDays As Integer Dim RateType As String, RateApplied As Double Dim OrderTotal As Double Dim OrderInvoice As String

RateType = "Weekly Rate" RateApplied = 0 OrderTotal = RateApplied

CustomerName = InputBox("Enter Customer Name:", _ "Bethesda Car Rental", "John Doe")

RentStartDate = CDate(InputBox("Enter Rent Start Date:", _ "Bethesda Car Rental", #1/1/1900#)) RentEndDate = CDate(InputBox("Enter Rend End Date:", _ "Bethesda Car Rental", #1/1/1900#)) NumberOfDays = DateDiff(DateInterval.Day, RentStartDate, RentEndDate)

RateApplied = CDbl(InputBox("Enter Rate Applied:", "Bethesda Car Rental", 0))

OrderInvoice = "===========================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Order Processing =-=-==" & vbCrLf & "------------------------------------------------" & vbCrLf & "Processed for:" & vbTab & CustomerName & vbCrLf & "------------------------------------------------" & vbCrLf & "Start Date:" & vbTab & RentStartDate & vbCrLf & "End Date:" & vbTab & RentEndDate & vbCrLf & "Nbr of Days:" & vbTab & NumberOfDays & vbCrLf & "------------------------------------------------" & vbCrLf & "Rate Type:" & vbTab & RateType & vbCrLf & "Rate Applied:" & vbTab & RateApplied & vbCrLf & "Order Total:" & vbTab & FormatCurrency(OrderTotal) & vbCrLf & "==========================="

MsgBox(OrderInvoice, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") Return 0 End Function

End Module

Page 183: Microsoft Visual Basic 2010 Tutorial

11. Close the message box and the DOS window to return to your programming environment

Choose an Alternate Value

We saw how to call a function named Choose where only one value is being considered. Thereality is that if there is an alternate value, the function produces a null result. Consider the sameprogram we used earlier but with a different value:

Module Exercise

Public Function Main() As Integer Dim Status As UShort, EmploymentStatus As String

Status = 2

EmploymentStatus = Choose(Status, "Full Time")

MsgBox(EmploymentStatus)

Return 0 End Function

End Module

This would produce:

Page 184: Microsoft Visual Basic 2010 Tutorial

Notice that the function returns nothing (an empty string). To use this function as an alternative tothe If...Then...Else operation, you can pass two values for the second argument. The secondargument is actually passed as a list of values. Each value has a specific position as its index. Touse the function in an If...Then...Else implementation, pass two values for the second argument.Here is an example:

Choose(Status, "Full Time", "Part Time")

The second argument to the function, which is the first value of the Choose argument, has anindex of 1. The third argument to the function, which is the second value of the Choose argument,has an index of 2.

When the Choose() function is called, if the first argument has a value of 1, then the secondargument is validated. If the first argument has a value of 2, then the third argument is validated.As mentioned already, you can retrieve the returned value of the function and use it however youwant. Here is an example:

Module Exercise

Public Function Main() As Integer Dim Status As UShort, EmploymentStatus As String

Status = 2

EmploymentStatus = Choose(Status, "Full Time", "Part Time")

MsgBox("Employment Status: " & EmploymentStatus)

Return 0 End Function

End Module

This would produce:

Switching to an Alternate Value

We saw earlier how to call the Switch function in an If...Then condition. Once again, the problemis that if you call it with a value that is not checked by the first argument, the function produces anull value (an empty string). To apply this function to an If...Then...Else scenario, you can call itusing the following formula:

Switch(Condition1ToCheck, Statement1, Condition2ToCheck, Statement2)

In the Condition1ToCheck placeholder, pass a Boolean expression that can be evaluated to True orFalse. If that condition is true, the second argument would be executed. To provide an alternativeto the first condition, pass another condition as Condition2ToCheck. If the Condition2ToCheck istrue, then Statement2 would be executed. Once gain, remember that you can get the valuereturned by the Switch function and use it. Here is an example:

Module Exercise Private Enum EmploymentStatus FullTime PartTime Contractor Seasonal Unknown End Enum

Public Function Main() As Integer Dim Status As EmploymentStatus Dim Result As String

Status = EmploymentStatus.PartTime Result = "Unknown"

Result = Microsoft.VisualBasic.Switch( _ Status = EmploymentStatus.FullTime, "Full Time", Status = EmploymentStatus.PartTime, "Part Time")

MsgBox("Employment Status: " & Result)

Return 0

Page 185: Microsoft Visual Basic 2010 Tutorial

End Function

End Module

This would produce:

Home Copyright © 2008-2010 FunctionX Next

Page 186: Microsoft Visual Basic 2010 Tutorial

Functional Conditions

Alternatives to a Condition Being True/False?

The If...Then...ElseIf Condition

The If...Then...ElseIf statement acts like the If...Then...Else expression, except that it offersas many choices as necessary. The formula is:

If Condition1 Then Statement1ElseIf Condition2 Then Statement2ElseIf Conditionk Then StatementkEnd If

The program will first examine Condition1. If Condition1 is true, the program will executeStatment1 and stop examining conditions. If Condition1 is false, the program will examineCondition2 and act accordingly. Whenever a condition is false, the program will continue examiningthe conditions until it finds one that is true. Once a true condition has been found and itsstatement executed, the program will terminate the conditional examination at End If. Here is anexample:

Module Exercise

Public Function Main() As Integer Dim MemberAge As Short

MemberAge = 32

If MemberAge <= 18 Then MsgBox("Membership: " & "Teen") ElseIf MemberAge < 55 Then MsgBox("Membership: " & "Adult") End If

Return 0 End Function

End Module

This would produce:

What If No Alternative is Valid?

There is still a possibility that none of the stated conditions be true. In this case, you shouldprovide a "catch all" condition. This is done with a last Else section. The Else section must be thelast in the list of conditions and would act if none of the primary conditions is true. The formula touse would be:

If Condition1 Then Statement1ElseIf Condition2 Then Statement2ElseIf Conditionk Then StatementkElse CatchAllStatementEnd If

Here is an example:

Module Exercise

Public Function Main() As Integer Dim MemberAge As Short

MemberAge = 65

If MemberAge <= 18 Then MsgBox("Membership: " & "Teen") ElseIf MemberAge < 55 Then MsgBox("Membership: " & "Adult")

Page 187: Microsoft Visual Basic 2010 Tutorial

Else MsgBox("Membership: " & "Senior") End If

Return 0 End Function

End Module

This would produce:

Practical Learning: Using If...Then...ElseIf

1. Start Microsoft Visual Basic and create a Console Application named BCR3

2. In the Solution Explorer, right-click Module1.vb and click Rename

3. Type BethesdaCarRental.vb and press Enter

4. Accept to change the file name

5. To use an If...Then...ElseIf condition, change the document as follows:

Module BethesdaCarRental

Public Function Main() As Integer Dim EmployeeNumber As Long, EmployeeName As String Dim CustomerName As String Dim RentStartDate As Date, RentEndDate As Date Dim NumberOfDays As Integer Dim RateType As String, RateApplied As Double Dim OrderTotal As Double Dim OrderInvoice As String

RateType = "Weekly Rate" RateApplied = 0 OrderTotal = RateApplied

EmployeeNumber = _ CLng(InputBox("Employee number (who processed this order):", "Bethesda Car Rental", "00000"))

If EmployeeNumber = 22804 Then EmployeeName = "Helene Mukoko" ElseIf EmployeeNumber = 92746 Then EmployeeName = "Raymond Kouma" ElseIf EmployeeNumber = 54080 Then EmployeeName = "Henry Larson" ElseIf EmployeeNumber = 86285 Then EmployeeName = "Gertrude Monay" Else EmployeeName = "Unknown" End If

CustomerName = InputBox("Enter Customer Name:", _ "Bethesda Car Rental", "John Doe")

RentStartDate = CDate(InputBox("Enter Rent Start Date:", _ "Bethesda Car Rental", #1/1/1900#)) RentEndDate = CDate(InputBox("Enter Rend End Date:", _ "Bethesda Car Rental", #1/1/1900#)) NumberOfDays = DateDiff(DateInterval.Day, RentStartDate, RentEndDate)

RateApplied = CDbl(InputBox("Enter Rate Applied:", _ "Bethesda Car Rental", 0))

OrderInvoice = "===========================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Order Processing =-=-==" & vbCrLf & "------------------------------------------------" & vbCrLf & "Processed by:" & vbTab & EmployeeName & vbCrLf & "Processed for:" & vbTab & CustomerName & vbCrLf & "------------------------------------------------" & vbCrLf & "Start Date:" & vbTab & RentStartDate & vbCrLf & "End Date:" & vbTab & RentEndDate & vbCrLf & "Nbr of Days:" & vbTab & NumberOfDays & vbCrLf & "------------------------------------------------" & vbCrLf & "Rate Type:" & vbTab & RateType & vbCrLf & "Rate Applied:" & vbTab & RateApplied & vbCrLf & "Order Total:" & vbTab & FormatCurrency(OrderTotal) & vbCrLf & "==========================="

MsgBox(OrderInvoice, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") Return 0 End Function

End Module

Page 188: Microsoft Visual Basic 2010 Tutorial

6. Execute the application

7. Enter the employee number as 54080, the customer name as James Wiley, the start date as11/05/2008, the end date as 11/15/2008, and the rate applied 49.95

8. Close the message box and the DOS window to return to your programming environment

Conditional Statements and Functions

Introduction

As introduced in Lesson 5 and as seen in lessons thereafter, we know that a function is used toperform a specific assignment and produce a result. Here is an example:

Private Function SetMembershipLevel$() Dim MemberAge%

MemberAge% = InputBox("Enter the Member's Age")

Return ""End Function

When performing its assignment, a function can encounter different situations, some of whichwould need to be checked for truthfulness or negation. This means that conditional statements canassist a procedure with its assignment.

1. Enter the customer name as Judith Nkolo, the rent start date as 11/05/2008, the rent enddate as 11/15/2008, and the rate applied 39.95

2. Close the message box and the DOS window to return to your programming environment

Conditional Returns

A function is meant to return a value. Sometimes, it will perform some tasks whose results wouldlead to different results. A function can return only one value (we saw that, by passing argumentsby reference, you can make a procedure return more than one value) but you can make it render aresult depending on a particular behavior. If a function is requesting an answer from the user,since the user can provide different answers, you can treat each result differently. Consider thefollowing function:

Module Exercise

Private Function SetMembershipLevel$() Dim MemberAge%

MemberAge% = InputBox("Enter the Member's Age")

If MemberAge% < 18 Then Return "Teen" ElseIf MemberAge% < 55 Then Return "Adult"

Page 189: Microsoft Visual Basic 2010 Tutorial

End If End Function

Public Function Main() As Integer Dim Membership$

MsgBox("Membership: " & Membership$) Return 0 End Function

End Module

At first glance, this function looks fine. The user is asked to provide a number. If the user enters anumber less than 18 (excluded), the function returns Teen. Here is an example of running theprogram:

If the user provides a number between 18 (included) and 55, the function returns the Adult. Hereis another example of running the program:

What if there is an answer that does not fit those we are expecting? The values that we havereturned in the function conform only to the conditional statements and not to the function.Remember that in If Condidion Statement, the Statement executes only if the Condition is true.Here is what will happen. If the user enters a number higher than 55 (excluded), the function willnot execute any of the returned statements. This means that the execution will reach the EndFunction line without encountering a return value. This also indicates to the compiler that youwrote a function that is supposed to return a value, but by the end of the method, it didn't returna value. Here is another example of running the program:

The compiler would produce a warning:

Warning 1 Function 'SetMembershipLevel' doesn't return a value on all code paths.

Page 190: Microsoft Visual Basic 2010 Tutorial

To solve this problem, you have various alternatives. If the function uses an If...Then condition,you can create an Else section that embraces any value other than those validated previously.Here is an example:

Module Exercise

Private Function SetMembershipLevel$() Dim MemberAge%

MemberAge% = InputBox("Enter the Member's Age")

If MemberAge% < 18 Then Return "Teen" ElseIf MemberAge% < 55 Then Return "Adult" Else Return "Senior" End If

End Function

Public Function Main() As Integer Dim Membership$

Membership$ = SetMembershipLevel$() MsgBox("Membership: " & Membership$) Return 0 End Function

End Module

This time, the Else condition would execute if no value applies to the If or ElseIf conditions andthe compiler would not produce a warning. Here is another example of running the program:

An alternative is to provide a last return value just before the End Function line. In this case, ifthe execution reaches the end of the function, it would still return something but you would knowwhat it returns. This would be done as follows:

Private Function SetMembershipLevel$() Dim MemberAge%

MemberAge% = InputBox("Enter the Member's Age")

If MemberAge% < 18 Then Return "Teen" ElseIf MemberAge% < 55 Then Return "Adult" End If

Return "Senior"End Function

If the function uses an If condition, both implementations would produce the same result.

Practical Learning: Using a Conditional Statement

1. To use a conditional statement in a function, change the document as follows:

Module BethesdaCarRental Private Function GetEmployeeName(ByVal EmplNbr As Long) As String Dim Name As String

If EmplNbr = 22804 Then Name = "Helene Mukoko" ElseIf EmplNbr = 92746 Then Name = "Raymond Kouma" ElseIf EmplNbr = 54080 Then Name = "Henry Larson" ElseIf EmplNbr = 86285 Then Name = "Gertrude Monay" Else Name = "Unknown" End If

Page 191: Microsoft Visual Basic 2010 Tutorial

2. Execute the application

3. Enter the employee number as 54080, the customer name as Sunil Ajat, the start date as11/05/2008, the end date as 11/15/2008, and the rate applied 49.95

4. Close the message box and the DOS window to return to your programming environment

If-Condition Built-In Functions

Return Name End Function

Public Function Main() As Integer Dim EmployeeNumber As Long, EmployeeName As String Dim CustomerName As String Dim RentStartDate As Date, RentEndDate As Date Dim NumberOfDays As Integer Dim RateType As String, RateApplied As Double Dim OrderTotal As Double Dim OrderInvoice As String

RateType = "Weekly Rate" RateApplied = 0 OrderTotal = RateApplied

EmployeeNumber = CLng(InputBox( "Employee number (who processed this order):", "Bethesda Car Rental", "00000"))

EmployeeName = GetEmployeeName(EmployeeNumber)

CustomerName = InputBox("Enter Customer Name:", _ "Bethesda Car Rental", "John Doe")

RentStartDate = CDate(InputBox("Enter Rent Start Date:", _ "Bethesda Car Rental", #1/1/1900#)) RentEndDate = CDate(InputBox("Enter Rend End Date:", _ "Bethesda Car Rental", #1/1/1900#)) NumberOfDays = DateDiff(DateInterval.Day, RentStartDate, RentEndDate)

RateApplied = CDbl(InputBox("Enter Rate Applied:", _ "Bethesda Car Rental", 0))

OrderInvoice = "===========================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Order Processing =-=-==" & vbCrLf & "------------------------------------------------" & vbCrLf & _ "Processed by:" & vbTab & EmployeeName & vbCrLf & "Processed for:" & vbTab & CustomerName & vbCrLf & "------------------------------------------------" & vbCrLf & "Start Date:" & vbTab & RentStartDate & vbCrLf & "End Date:" & vbTab & RentEndDate & vbCrLf & "Nbr of Days:" & vbTab & NumberOfDays & vbCrLf & "------------------------------------------------" & vbCrLf & "Rate Type:" & vbTab & RateType & vbCrLf & "Rate Applied:" & vbTab & RateApplied & vbCrLf & "Order Total:" & vbTab & FormatCurrency(OrderTotal) & vbCrLf & "==========================="

MsgBox(OrderInvoice, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") Return 0 End Function

End Module

Page 192: Microsoft Visual Basic 2010 Tutorial

Using the Immediate If Function

The IIf() function can also be used in place of an If...Then...ElseIf scenario. When the functionis called, the Expression is checked. As we saw already, if the expression is true, the functionreturns the value of the TruePart argument and ignores the last argument. To use this function asan alternative to If...Then...ElseIf statement, if the expression is false, instead of immediatelyreturning the value of the FalsePart argument, you can translate that part into a new IIf function.The pseudo-syntax would become:

Public Function IIf( _ ByVal Expression As Boolean, _ ByVal TruePart As Object, _ Public Function IIf( _ ByVal Expression As Boolean, _ ByVal TruePart As Object, _ ByVal FalsePart As Object _ ) As Object) As Object

In this case, if the expression is false, the function returns the TruePart and stops. If theexpression is false, the compiler accesses the internal IIf function and applies the same scenario.Here is example:

Module Exercise

Public Function Main() As Integer Dim MemberAge As Short Dim MembershipCategory As String

MemberAge = 74

MembershipCategory = _ IIf(MemberAge <= 18, "Teen", IIf(MemberAge < 55, "Adult", "Senior"))

MsgBox("Membership: " & MembershipCategory) Return 0 End Function

End Module

We saw that in an If...Then...ElseIf statement you can add as many ElseIf conditions as youwant. In the same, you can call as many IIf functions in the subsequent FalsePart sections as youjudge necessary:

Public Function IIf( ByVal Expression As Boolean, ByVal TruePart As Object, Public Function IIf( ByVal Expression As Boolean, ByVal TruePart As Object, Public Function IIf( ByVal Expression As Boolean, ByVal TruePart As Object, Public Function IIf( ByVal Expression As Boolean, ByVal TruePart As Object, ByVal FalsePart As Object ) As Object ) As Object ) As Object) As Object

Choose an Alternate Value

As we have seen so far, the Choose function takes a list of arguments. To use it as an alternativeto the If...Then...ElseIf...ElseIf condition, you can pass as many values as you judge necessaryfor the second argument. The index of the first member of the second argument would be 1. Theindex of the second member of the second argument would be 2, and so on. When the function iscalled, it would first get the value of the first argument, then it would check the indexes of theavailable members of the second argument. The member whose index matches the first argumentwould be executed. Here is an example:

Module Exercise

Public Function Main() As Integer Dim Status As UShort, EmploymentStatus As String

Status = 3

EmploymentStatus = Choose(Status, "Full Time", "Part Time", "Contractor", "Seasonal")

MsgBox("Employment Status: " & EmploymentStatus)

Return 0 End Function

End Module

Page 193: Microsoft Visual Basic 2010 Tutorial

This would produce:

So far, we have used only strings for the values of the second argument of the Choose()function. In reality, the values of the second argument can be almost anything. One value can be aconstant. Another value can be a string. Yet another value can come from calling a function. Hereis an example:

Module Exercise

Private Function ShowContractors$() Return "=-= List of Contractors =-=" & vbCrLf & "Martin Samson" & vbCrLf & "Geneviève Lam" & vbCrLf & "Frank Viel" & vbCrLf & "Henry Rickson" & vbCrLf & "Samuel Lott" End Function

Public Function Main() As Integer Dim Status As UShort, Result$

Status = 3

Result = Choose(Status, "Employment Status: Full Time", "Employment Status: Part Time", ShowContractors, "Seasonal Employment") MsgBox(Result)

Return 0 End Function

End Module

This would produce:

The values of the second argument can even be of different types.

Practical Learning: Using the Choose Function

1. To use the Choose() function, change the document as follows:

Module BethesdaCarRental Private Function GetEmployeeName(ByVal EmplNbr As Long) As String Dim Name As String

If EmplNbr = 22804 Then Name = "Helene Mukoko" ElseIf EmplNbr = 92746 Then Name = "Raymond Kouma" ElseIf EmplNbr = 54080 Then Name = "Henry Larson" ElseIf EmplNbr = 86285 Then Name = "Gertrude Monay" Else Name = "Unknown" End If

Return Name End Function

Public Function Main() As Integer Dim EmployeeNumber As Long, EmployeeName As String Dim CustomerName As String Dim Tank As Integer, TankLevel As String Dim RentStartDate As Date, RentEndDate As Date Dim NumberOfDays As Integer Dim RateType As String, RateApplied As Double Dim OrderTotal As Double Dim OrderInvoice As String

Page 194: Microsoft Visual Basic 2010 Tutorial

2. Eexecute the application

3. Enter the employee number as 22804, the customer name as George Livingstone, the tanklevel as 2, the start date as 09/15/2008, the end date as 09/19/2008, and the rateapplied 65.75

4. Close the message box and the DOS window to return to your programming environment

Switching to an Alternate Value

The Switch() function is a prime alternative to the If...Then...ElseIf...ElseIf condition. The

RateType = "Weekly Rate" RateApplied = 0 OrderTotal = RateApplied

EmployeeNumber = CLng(InputBox("Employee number (who processed this order):", "Bethesda Car Rental", "00000"))

EmployeeName = GetEmployeeName(EmployeeNumber)

CustomerName = InputBox("Enter Customer Name:", "Bethesda Car Rental", "John Doe") Tank = CInt(InputBox("Enter Tank Level:" & vbCrLf & "1. Empty" & vbCrLf & "2. 1/4 Empty" & vbCrLf & "3. 1/2 Full" & vbCrLf & "4. 3/4 Full" & vbCrLf & "5. Full", "Bethesda Car Rental", 1)) TankLevel = Choose(Tank, "Empty", "1/4 Empty", "1/2 Full", "3/4 Full", "Full")

RentStartDate = CDate(InputBox("Enter Rent Start Date:", "Bethesda Car Rental", #1/1/1900#)) RentEndDate = CDate(InputBox("Enter Rend End Date:", "Bethesda Car Rental", #1/1/1900#)) NumberOfDays = DateDiff(DateInterval.Day, RentStartDate, RentEndDate)

RateApplied = CDbl(InputBox("Enter Rate Applied:", _ "Bethesda Car Rental", 0))

OrderInvoice = "===========================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Order Processing =-=-==" & vbCrLf & "------------------------------------------------" & vbCrLf & "Processed by:" & vbTab & EmployeeName & vbCrLf & "Processed for:" & vbTab & CustomerName & vbCrLf & "------------------------------------------------" & vbCrLf & "Car Selected:" & vbCrLf & vbTab & "Tank:" & vbTab & TankLevel & vbCrLf & "------------------------------------------------" & vbCrLf & "Start Date:" & vbTab & RentStartDate & vbCrLf & "End Date:" & vbTab & RentEndDate & vbCrLf & "Nbr of Days:" & vbTab & NumberOfDays & vbCrLf & "------------------------------------------------" & vbCrLf & "Rate Type:" & vbTab & RateType & vbCrLf & "Rate Applied:" & vbTab & RateApplied & vbCrLf & "Order Total:" & vbTab & FormatCurrency(OrderTotal) & vbCrLf & "==========================="

MsgBox(OrderInvoice, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") Return 0 End Function

End Module

Page 195: Microsoft Visual Basic 2010 Tutorial

argument to this function is passed as a list of values. As seen previously, each value is passed asa combination of two values:

ConditionXToCheck, StatementX

As the function is accessed, the compiler checks each condition. If a condition X is true, itsstatement is executed. If a condition Y is false, the compiler skips it. You can provide as many ofthese combinations as you want. Here is an example:

Module Exercise Private Enum EmploymentStatus FullTime PartTime Contractor Seasonal End Enum

Public Function Main() As Integer Dim Status As EmploymentStatus Dim Result As String

Status = EmploymentStatus.Contractor Result = "Unknown"

Result = Microsoft.VisualBasic.Switch( Status = EmploymentStatus.FullTime, "Full Time", Status = EmploymentStatus.PartTime, "Part Time", Status = EmploymentStatus.Contractor, "Contractor", Status = EmploymentStatus.Seasonal, "Seasonal")

MsgBox("Employment Status: " & Result)

Return 0 End Function

End Module

This would produce:

In a true If...Then...ElseIf...ElseIf condition, we saw that there is a possibility that none of theconditions would fit, in which case you can add a last Else statement. The Switch() function alsosupports this situation if you are using a number, a character, or a string. To provide this lastalternative, instead of a ConditionXToCheck expressionk, enter True, and include the necessarystatement. Here is an example:

Module Exercise

Public Function Main() As Integer Dim Status As UShort Dim Result As String

Status = 12

Result = Microsoft.VisualBasic.Switch( Status = 1, "Full Time", Status = 2, "Part Time", Status = 3, "Contractor", Status = 4, "Seasonal", True, "Unknown")

MsgBox("Employment Status: " & Result)

Return 0 End Function

End Module

This would produce:

Remember that you can also use True with a character. Here is an example:

Module Exercise

Public Function Main() As Integer Dim Gender As Char Dim Result As String

Gender = "H"

Page 196: Microsoft Visual Basic 2010 Tutorial

Result = Microsoft.VisualBasic.Switch( Gender = "f", "Female", Gender = "F", "Female", Gender = "m", "Male", Gender = "M", "Male", True, "Unknown")

MsgBox("Gender: " & Result)

Return 0 End Function

End Module

This would produce:

Practical Learning: Using the Switch() Function

1. To use the Switch() function, change the document as follows:

Module BethesdaCarRental Private Function GetEmployeeName(ByVal EmplNbr As Long) As String Dim Name As String

If EmplNbr = 22804 Then Name = "Helene Mukoko" ElseIf EmplNbr = 92746 Then Name = "Raymond Kouma" ElseIf EmplNbr = 54080 Then Name = "Henry Larson" ElseIf EmplNbr = 86285 Then Name = "Gertrude Monay" Else Name = "Unknown" End If

Return Name End Function

Public Function Main() As Integer Dim EmployeeNumber As Long, EmployeeName As String Dim CustomerName As String Dim TagNumber As String, CarSelected As String Dim Tank As Integer, TankLevel As String Dim RentStartDate As Date, RentEndDate As Date Dim NumberOfDays As Integer Dim RateType As String, RateApplied As Double Dim OrderTotal As Double Dim OrderInvoice As String

RateType = "Weekly Rate" RateApplied = 0 OrderTotal = RateApplied

EmployeeNumber = CLng(InputBox("Employee number (who processed this order):", "Bethesda Car Rental", "00000"))

EmployeeName = GetEmployeeName(EmployeeNumber)

CustomerName = InputBox("Enter Customer Name:", "Bethesda Car Rental", "John Doe")

TagNumber = InputBox("Enter the tag number of the car to rent:", "Bethesda Car Rental", "000000")

CarSelected = Microsoft.VisualBasic.Switch( TagNumber = "297419", "BMW 335i", TagNumber = "485M270", "Chevrolet Avalanche", TagNumber = "247597", "Honda Accord LX", TagNumber = "924095", "Mazda Miata", TagNumber = "772475", "Chevrolet Aveo", TagNumber = "M931429", "Ford E150XL", TagNumber = "240759", "Buick Lacrosse", True, "Unidentified Car")

Tank = CInt(InputBox("Enter Tank Level:" & vbCrLf & "1. Empty" & vbCrLf & "2. 1/4 Empty" & vbCrLf & "3. 1/2 Full" & vbCrLf & "4. 3/4 Full" & vbCrLf & "5. Full", "Bethesda Car Rental", 1)) TankLevel = Choose(Tank, "Empty", "1/4 Empty", "1/2 Full", "3/4 Full", "Full")

RentStartDate = CDate(InputBox("Enter Rent Start Date:", "Bethesda Car Rental", #1/1/1900#)) RentEndDate = CDate(InputBox("Enter Rend End Date:", _

Page 197: Microsoft Visual Basic 2010 Tutorial

2. Eexecute the application

3. Enter the employee number as 86285, the customer name as Genevieve H. Gomoore, thetag number as 924095, the tank level as 3, the start date as 10/22/2008, the end date as10/31/2008, and the rate applied 55.50

4. Close the message box and the DOS window to return to your programming environment

Previous Copyright © 2008-2010 FunctionX Next

"Bethesda Car Rental", #1/1/1900#)) NumberOfDays = DateDiff(DateInterval.Day, RentStartDate, RentEndDate)

RateApplied = CDbl(InputBox("Enter Rate Applied:", _ "Bethesda Car Rental", 0))

OrderInvoice = "===========================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Order Processing =-=-==" & vbCrLf & "------------------------------------------------" & vbCrLf & "Processed by:" & vbTab & EmployeeName & vbCrLf & "Processed for:" & vbTab & CustomerName & vbCrLf & "------------------------------------------------" & vbCrLf & "Car Selected:" & vbCrLf & vbTab & "Tag #:" & vbTab & TagNumber & vbCrLf & vbTab & "Car:" & vbTab & CarSelected & vbCrLf & vbTab & "Tank:" & vbTab & TankLevel & vbCrLf & "------------------------------------------------" & vbCrLf & "Start Date:" & vbTab & RentStartDate & vbCrLf & "End Date:" & vbTab & RentEndDate & vbCrLf & "Nbr of Days:" & vbTab & NumberOfDays & vbCrLf & "------------------------------------------------" & vbCrLf & "Rate Type:" & vbTab & RateType & vbCrLf & "Rate Applied:" & vbTab & RateApplied & vbCrLf & "Order Total:" & vbTab & FormatCurrency(OrderTotal) & vbCrLf & "==========================="

MsgBox(OrderInvoice, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") Return 0 End Function

End Module

Page 198: Microsoft Visual Basic 2010 Tutorial

Conditional Selections

The Select...Case Statement

Introduction

If you have a large number of conditions to examine, the If...Then...Else statement will go througheach one of them. The Visual Basic language offers the alternative of jumping to the statement thatapplies to the state of the condition. This is done with the Select and Case keywords.

The formula of the Select Case statement is:

Select Case Expression Case Expression1 Statement1 Case Expression2 Statement2 Case ExpressionX StatementXEnd Select

The statement starts with Select Case and ends with End Select. On the right side of Select Case,enter a value, the Expression factor, that will be used as a tag. The value of Expression can beBoolean value (a Boolean type), a character (Char type), a string (a String type), a natural number(a Byte, an SByte, a Short, a UShort, an Integer, a UInteger, a Long, or a ULong type), adecimal number (a Single, a Double, or a Decimal type), a date or time value (a Date type), anenumeration (an Enum type), or else (an Object type). Inside the Select Case and the End Selectlines, you provide one or more sections that each contains a Case keyword followed by a value. Thevalue on the right side of Case, ExpresionX, must be the same type as the value of Expression or itcan be implied from it. After the case and its expression, you can write a statement.

When this section of code is accessed, the value of Expression is considered. Then the value ofExpression is compared to each ExpressionX of each case:

a. If the value of Expression1 is equal to that of Expression, then Statement1 is executed. If thevalue of Expression1 is not equal to that of Expression, then the compiler moves to Expression2

b. If the value of Expression2 is equal to that of Expression, then Statement2 is executed

c. This will continue down to the last ExpressionX

Here is an example:

Module Exercise

Public Function Main() As Integer Dim Answer As Byte

Answer = CByte(InputBox( _ "One of the following is not a Visual Basic keyword" & vbCrLf & "1) Function" & vbCrLf & "2) Except" & vbCrLf & "3) ByRef" & vbCrLf & "4) Each" & vbCrLf & vbCrLf & "Your Answer? "))

Select Case Answer Case 1 MsgBox("Wrong: Function is a Visual Basic keyword." & vbCrLf & "It is used to create a procedure of a function type") Case 2 MsgBox("Correct: Except is not a keyword in " & vbCrLf & "Visual Basic but __except is a C++ " & vbCrLf & "keyword used in Exception Handling") Case 3 MsgBox("Wrong: ByRef is a Visual Basic keyword used " & vbCrLf & "to pass an argument by reference to a procedure") Case 4 MsgBox("Wrong: The ""Each"" keyword is used in " & vbCrLf & "Visual Basic in a type of looping " & vbCrLf & "used to ""scan"" a list of item.") End Select

Return 0 End Function

End Module

Here is an example of running the program:

Page 199: Microsoft Visual Basic 2010 Tutorial

What Case Else?

The above code supposes that one of the cases will match the value of the Expression factor. This isnot always so. If you anticipate that there could be no match between the Expression and one of theExpressions, you can use a Case Else statement at the end of the list. The statement would thenlook like this:

Select Case Expression Case Expression1 Statement1 Case Expression2 Statement2 Case Expressionk Statementk Case Else StatementkEnd Select

In this case, the statement after the Case Else will execute if none of the previous expressionsmatches the Expression factor. Here is an example:

Module Exercise

Public Function Main() As Integer Dim Answer As Byte

Answer = CByte(InputBox( _ "One of the following is not a Visual Basic keyword" & vbCrLf & "1) Function" & vbCrLf & "2) Except" & vbCrLf & "3) ByRef" & vbCrLf & "4) Each" & vbCrLf & vbCrLf & "Your Answer? "))

Select Case Answer Case 1 MsgBox("Wrong: Function is a Visual Basic keyword." & vbCrLf & "It is used to create a procedure of a function type") Case 2 MsgBox("Correct: Except is not a keyword in " & vbCrLf & "Visual Basic but __except is a C++ " & vbCrLf & "keyword used in Exception Handling") Case 3 MsgBox("Wrong: ByRef is a Visual Basic keyword used " & vbCrLf & "to pass an argument by reference to a procedure") Case 4 MsgBox("Wrong: The ""Each"" keyword is used in " & vbCrLf & "Visual Basic in a type of looping " & vbCrLf & "used to ""scan"" a list of item.") Case Else MsgBox("Invalid Selection") End Select

Return 0 End Function

End Module

Here is an example of running the program:

Page 200: Microsoft Visual Basic 2010 Tutorial

Practical Learning: Using a Select...Case Condition

1. Start Microsoft Visual Basic and create a Console Application named BCR4

2. In the Solution Explorer, right-click Module1.vb and click Rename

3. Type BethesdaCarRental.vb and press Enter

4. Accept to change the name of the module

5. To use a Select...Case condition, change the document as follows:

Module BethesdaCarRental Private Function GetEmployeeName(ByVal EmplNbr As Long) As String Dim Name As String

If EmplNbr = 22804 Then Name = "Helene Mukoko" ElseIf EmplNbr = 92746 Then Name = "Raymond Kouma" ElseIf EmplNbr = 54080 Then Name = "Henry Larson" ElseIf EmplNbr = 86285 Then Name = "Gertrude Monay" Else Name = "Unknown" End If

Return Name End Function

Public Function Main() As Integer Dim EmployeeNumber As Long, EmployeeName As String Dim CustomerName As String Dim TagNumber As String, CarSelected As String Dim CarStatus As Integer, CarCondition As String Dim Tank As Integer, TankLevel As String Dim RentStartDate As Date, RentEndDate As Date Dim NumberOfDays As Integer Dim RateType As String, RateApplied As Double Dim OrderTotal As Double Dim OrderInvoice As String

RateType = "Weekly Rate" RateApplied = 0 OrderTotal = RateApplied

EmployeeNumber = CLng(InputBox("Employee number (who processed this order):", "Bethesda Car Rental", "00000"))

EmployeeName = GetEmployeeName(EmployeeNumber)

CustomerName = InputBox("Enter Customer Name:", "Bethesda Car Rental", "John Doe")

TagNumber = InputBox("Enter the tag number of the car to rent:", "Bethesda Car Rental", "000000")

CarSelected = Microsoft.VisualBasic.Switch( TagNumber = "297419", "BMW 335i", TagNumber = "485M270", "Chevrolet Avalanche", TagNumber = "247597", "Honda Accord LX", TagNumber = "924095", "Mazda Miata", TagNumber = "772475", "Chevrolet Aveo", TagNumber = "M931429", "Ford E150XL", TagNumber = "240759", "Buick Lacrosse", True, "Unidentified Car")

CarStatus = CInt(InputBox("After inpecting it, enter car condition:" & vbCrLf & "1. Excellent - No scratch, no damage, no concern" & vbCrLf & "2. Good - Some concerns (scratches or missing something)." & "Make sure the customer is aware." & vbCrLf &

Page 201: Microsoft Visual Basic 2010 Tutorial

6. Execute the application

7. Enter the employee number as 92746, the customer name as Antoinette D. Liel, the tagnumber as 297419, the car condition as 1, the tank level as 5, the start date as 11/15/2008,the end date as 11/17/2008, and the rate applied 65.75

"3. Drivable - The car is good enough to drive." & "The customer must know the status of the car " & "and agree to rent it", "Bethesda Car Rental", 1))

Select Case CarStatus Case 1 CarCondition = "Excellent" Case 2 CarCondition = "Good" Case 3 CarCondition = "Drivable" Case Else CarCondition = "Unknown" End Select

Tank = CInt(InputBox("Enter Tank Level:" & vbCrLf & "1. Empty" & vbCrLf & "2. 1/4 Empty" & vbCrLf & "3. 1/2 Full" & vbCrLf & "4. 3/4 Full" & vbCrLf & "5. Full", "Bethesda Car Rental", 1)) TankLevel = Choose(Tank, "Empty", "1/4 Empty", "1/2 Full", "3/4 Full", "Full")

RentStartDate = CDate(InputBox("Enter Rent Start Date:", "Bethesda Car Rental", #1/1/1900#)) RentEndDate = CDate(InputBox("Enter Rend End Date:", "Bethesda Car Rental", #1/1/1900#)) NumberOfDays = DateDiff(DateInterval.Day, RentStartDate, RentEndDate)

RateApplied = CDbl(InputBox("Enter Rate Applied:", "Bethesda Car Rental", 0))

OrderInvoice = "===========================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Order Processing =-=-==" & vbCrLf & "------------------------------------------------" & vbCrLf & "Processed by:" & vbTab & EmployeeName & vbCrLf & "Processed for:" & vbTab & CustomerName & vbCrLf & "------------------------------------------------" & vbCrLf & "Car Selected:" & vbCrLf & _ vbTab & "Tag #:" & vbTab & TagNumber & vbCrLf & vbTab & "Car:" & vbTab & CarSelected & vbCrLf & vbTab & "Tank:" & vbTab & TankLevel & vbCrLf & "Car Condition:" & vbTab & CarCondition & vbCrLf & "------------------------------------------------" & vbCrLf & "Start Date:" & vbTab & RentStartDate & vbCrLf & "End Date:" & vbTab & RentEndDate & vbCrLf & "Nbr of Days:" & vbTab & NumberOfDays & vbCrLf & "------------------------------------------------" & vbCrLf & "Rate Type:" & vbTab & RateType & vbCrLf & "Rate Applied:" & vbTab & RateApplied & vbCrLf & "Order Total:" & vbTab & FormatCurrency(OrderTotal) & vbCrLf & "==========================="

MsgBox(OrderInvoice, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") Return 0 End Function

End Module

Page 202: Microsoft Visual Basic 2010 Tutorial

8. Close the message box and the DOS window to return to your programming environment

Combining Cases

As mentioned in our introduction, the Select Case can use a value other than an integer. For exampleyou can use a character. Here is an example:

Module Exercise

Public Function Main() As Integer Dim Gender As Char

Gender = "M"

Select Case Gender Case "F" MsgBox("Female") Case "M" MsgBox("Male") Case Else MsgBox("Unknown") End Select

Return 0 End Function

End Module

This would produce:

Notice that in this case we are using only upper case characters. If want to validate lower casecharacters also, we may have to create additional case sections for each. Here is an example:

Module Exercise

Public Function Main() As Integer Dim Gender As Char

Gender = "f"

Select Case Gender Case "f" MsgBox("Female") Case "F" MsgBox("Female") Case "m" MsgBox("Male") Case "M" MsgBox("Male") Case Else MsgBox("Unknown") End Select

Return 0 End Function

Page 203: Microsoft Visual Basic 2010 Tutorial

End Module

This would produce:

Instead of using one value for a case, you can apply more than one. To do this, on the right side ofthe Case keyword, you can separate the expressions with commas. Here are examples:

Module Exercise

Public Function Main() As Integer Dim Gender As Char

Gender = "F"

Select Case Gender Case "f", "F" MsgBox("Female") Case "m", "M" MsgBox("Male") Case Else MsgBox("Unknown") End Select

Return 0 End Function

End Module

Validating a Range of Cases

You can use a range of values for a case. To do this, on the right side of Case, enter the lower value,followed by To, followed by the higher value. Here is an example:

Imports System

Module Exercise

Public Function Main() As Integer Dim Age As Integer Age = 24

Select Case Age Case 0 To 17 MsgBox("Teen") Case 18 To 55 MsgBox("Adult") Case Else MsgBox("Senior") End Select End Sub

End Module

Checking Whether a Value IS

Consider the following program:

Module Exercise

Public Function Main() As Integer Dim Number As Short

Number = 448

Select Case Number Case -602 MsgBox("-602") Case 24 MsgBox("24") Case 0 MsgBox("0") End Select

Return 0 End Function

End Module

Obviously this Select Case statement will work in rare cases where the expression of a case exactlymatches the value sought for. In reality, for this type of scenario, you could validate a range ofvalues. The Visual Basic language provides an alternative. You can check whether the value of theExpression responds to a criterion instead of an exact value. To create it, you use the Is operatorwith the following formula:

Is Operator Value

Page 204: Microsoft Visual Basic 2010 Tutorial

You start with the Is keyword. It is followed by one of the Boolean operators we saw in the previouslessons: =, <>, <, <=, >, or >=. On the right side of the boolean operator, type the desired value.Here are examples:

Module Exercise

Public Function Main() As Integer Dim Number As Short

Number = -448

Select Case Number Case Is < 0 MsgBox("The number is negative") Case Is > 0 MsgBox("The number is positive") Case Else MsgBox("0") End Select

Return 0 End Function

End Module

Although we used a natural number here, you can use any appropriate logical comparison that canproduce a True or a False result. You can also combine it with the other alternatives we sawpreviously, such as separating the expressions of a case with commas.

Practical Learning: Using Options of Select...Case

1. To use various options of the Select...Case condition, change the document as follows:

Module BethesdaCarRental Private Function GetEmployeeName(ByVal EmplNbr As Long) As String Dim Name As String

If EmplNbr = 22804 Then Name = "Helene Mukoko" ElseIf EmplNbr = 92746 Then Name = "Raymond Kouma" ElseIf EmplNbr = 54080 Then Name = "Henry Larson" ElseIf EmplNbr = 86285 Then Name = "Gertrude Monay" Else Name = "Unknown" End If

Return Name End Function

Public Function Main() As Integer Dim EmployeeNumber As Long, EmployeeName As String Dim CustomerName As String Dim TagNumber As String, CarSelected As String Dim CarStatus As Integer, CarCondition As String Dim Tank As Integer, TankLevel As String Dim RentStartDate As Date, RentEndDate As Date Dim NumberOfDays As Integer Dim RateType As String, RateApplied As Double Dim OrderTotal As Double Dim OrderInvoice As String

RateType = "Weekly Rate" RateApplied = 0 OrderTotal = RateApplied

EmployeeNumber = CLng(InputBox("Employee number (who processed this order):", "Bethesda Car Rental", "00000"))

EmployeeName = GetEmployeeName(EmployeeNumber)

CustomerName = InputBox("Enter Customer Name:", "Bethesda Car Rental", "John Doe")

TagNumber = InputBox("Enter the tag number of the car to rent:", "Bethesda Car Rental", "000000")

CarSelected = Microsoft.VisualBasic.Switch( TagNumber = "297419", "BMW 335i", TagNumber = "485M270", "Chevrolet Avalanche", TagNumber = "247597", "Honda Accord LX", TagNumber = "924095", "Mazda Miata", TagNumber = "772475", "Chevrolet Aveo", TagNumber = "M931429", "Ford E150XL", TagNumber = "240759", "Buick Lacrosse", True, "Unidentified Car")

CarStatus = CInt(InputBox("After inpecting it, enter car condition:" & vbCrLf & "1. Excellent - No scratch, no damage, no concern" & vbCrLf & "2. Good - Some concerns (scratches or missing something)." & "Make sure the customer is aware." & vbCrLf &

Page 205: Microsoft Visual Basic 2010 Tutorial

2. Execute the application

3. Enter the employee number as 86285, the customer name as Franco Bolero, the tag numberas M931429, the car condition as 3, the tank level as 1, the start date as 10/06/2008, theend date as 11/07/2008, and the rate applied 85.50

"3. Drivable - The car is good enough to drive." & "The customer must know the status of the car " & "and agree to rent it", "Bethesda Car Rental", 1))

Select Case CarStatus Case 1 CarCondition = "Excellent" Case 2 CarCondition = "Good" Case 3 CarCondition = "Drivable" Case Else CarCondition = "Unknown" End Select

Tank = CInt(InputBox("Enter Tank Level:" & vbCrLf & "1. Empty" & vbCrLf & "2. 1/4 Empty" & vbCrLf & "3. 1/2 Full" & vbCrLf & "4. 3/4 Full" & vbCrLf & "5. Full", "Bethesda Car Rental", 1)) TankLevel = Choose(Tank, "Empty", "1/4 Empty", "1/2 Full", "3/4 Full", "Full")

RentStartDate = CDate(InputBox("Enter Rent Start Date:", "Bethesda Car Rental", #1/1/1900#)) RentEndDate = CDate(InputBox("Enter Rend End Date:", "Bethesda Car Rental", #1/1/1900#)) NumberOfDays = DateDiff(DateInterval.Day, RentStartDate, RentEndDate)

RateApplied = CDbl(InputBox("Enter Rate Applied:", "Bethesda Car Rental", 0)) Dim TemporaryRate As Double

Select Case NumberOfDays Case 0, 1 RateType = "Daily Rate" OrderTotal = RateApplied Case 2 RateType = "Weekend Rate" TemporaryRate = RateApplied * 50 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * 2 Case 2 To 7 RateType = "Weekly Rate" TemporaryRate = RateApplied * 25 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * NumberOfDays Case Is > 8 RateType = "Monthly Rate" TemporaryRate = RateApplied * 15 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * NumberOfDays End Select

OrderInvoice = "===========================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Order Processing =-=-==" & vbCrLf & "------------------------------------------------" & vbCrLf & "Processed by:" & vbTab & EmployeeName & vbCrLf & "Processed for:" & vbTab & CustomerName & vbCrLf & "------------------------------------------------" & vbCrLf & "Car Selected:" & vbCrLf & vbTab & "Tag #:" & vbTab & TagNumber & vbCrLf & vbTab & "Car:" & vbTab & CarSelected & vbCrLf & vbTab & "Tank:" & vbTab & TankLevel & vbCrLf & "Car Condition:" & vbTab & CarCondition & vbCrLf & "------------------------------------------------" & vbCrLf & "Start Date:" & vbTab & RentStartDate & vbCrLf & "End Date:" & vbTab & RentEndDate & vbCrLf & "Nbr of Days:" & vbTab & NumberOfDays & vbCrLf & "------------------------------------------------" & vbCrLf & "Rate Type:" & vbTab & RateType & vbCrLf & "Rate Applied:" & vbTab & RateApplied & vbCrLf & "Order Total:" & vbTab & FormatCurrency(OrderTotal) & vbCrLf & "==========================="

MsgBox(OrderInvoice, _ MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") Return 0 End Function

End Module

Page 206: Microsoft Visual Basic 2010 Tutorial

4. Close the message box and the DOS window to return to your programming environment

Select...Case and the Conditional Built-In Functions

With the Select...Case statement, we saw how to check different values against a central one andtake action when one of those matches the tag. Here is an example:

Module Exercise

Public Function Main() As Integer Dim Number As UShort, MembershipType As String

Number = 2

Select Case Number Case 1 MembershipType = "Teen" Case 2 MembershipType = "Adult" Case Else MembershipType = "Senior" End Select

MsgBox("Membership Type: " & MembershipType) Return 0 End Function

End Module

We also saw that the Visual Basic language provides the Choose() function that can check acondition and take an action. The Choose() function is another alternative to a Select...Casestatement. Once again, consider the syntax of the Choose function:

Public Function Choose( _ ByVal Index As Double, _ ByVal ParamArray Choice() As Object _) As Object

This function takes two required arguments. The first argument is equivalent to the Expression of ourSelect Case formula. As mentioned already, the first argument must be a number (a Byte, an SByte,a Short, a UShort, an Integer, a UInteger, a Long, a ULong, a Single, a Double, or a Decimalvalue). This is the central value against which the other values will be compared. Instead of usingCase sections, provide the equivalent ExpressionX values as a list of values in place of the secondargument. The values are separated by commas. Here is an example:

Choose(Number, "Teen", "Adult", "Senior")

As mentioned already, the values of the second argument are provided as a list. Each member of thelist uses an index. The first member of the list, which is the second argument of this function, has anindex of 1. The second value of the argument, which is the third argument of the function, has anindex of 2. You can continue adding the values of the second argument as you see fit.

When the Choose() function has been called, it returns a value of type Object. You can retrieve thatvalue, store it in a variable and use it as you see fit. Here is an example:

Module Exercise

Public Function Main() As Integer Dim Number As UShort, MembershipType As String

Number = 1

Page 207: Microsoft Visual Basic 2010 Tutorial

MembershipType = Choose(Number, "Teen", "Adult", "Senior")

MsgBox("Membership Type: " & MembershipType) Return 0 End Function

End Module

Loops Repeaters

Introduction

A loop is a technique used to repeat an action. The Visual Basic language presents many variationsof loops. They combine the Do and the Loop keywords.

Practical Learning: Introducing Looping Statements

1. Create a new Console Application named BCR5

2. In the Solution Explorer, right-click Module1.vb and click Rename

3. Type BethesdaCarRental.vb and press Enter

4. Accept to change the name of the module and change the document as follows:

Module BethesdaCarRental

Public Function Main() As Integer Dim EmployeeName As String Dim StrHourlySalary As String, StrWeeklyHours As String Dim HourlySalary As Double Dim WeeklyHours As Double Dim RegularTime As Double, Overtime As Double Dim RegularPay As Double, OvertimePay As Double Dim NetPay As Double

Dim Payroll As String

HourlySalary = "0.00" WeeklyHours = "0.00"

EmployeeName = InputBox("Enter Employee Name:", "Bethesda Car Rental", "John Doe")

StrHourlySalary = InputBox("Enter Employee Hourly Salary:", "Bethesda Car Rental", "0.00")

If IsNumeric(StrHourlySalary) Then HourlySalary = CDbl(StrHourlySalary) Else MsgBox("The number " & StrHourlySalary & " you entered " & "for the hourly salary is not valid", MsgBoxStyle.Exclamation Or MsgBoxStyle.Critical, "Bethesda Car Rental") End If

StrWeeklyHours = InputBox("Enter Employee Weekly Hours:", "Bethesda Car Rental", "0.00")

If IsNumeric(StrWeeklyHours) Then WeeklyHours = CDbl(StrWeeklyHours) Else MsgBox("The value " & StrWeeklyHours & " you provided " & "for the weekly hours is not valid", MsgBoxStyle.Exclamation Or MsgBoxStyle.Critical, "Bethesda Car Rental") End If

If WeeklyHours < 40 Then RegularTime = WeeklyHours Overtime = 0 RegularPay = HourlySalary * RegularTime OvertimePay = 0 NetPay = RegularPay Else RegularTime = 40 Overtime = WeeklyHours - 40 RegularPay = HourlySalary * 40 OvertimePay = HourlySalary * Overtime NetPay = RegularPay + OvertimePay End If

Payroll = "======================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Employee Payroll =-=-==" & vbCrLf & "-------------------------------------------" & vbCrLf & "Employee Name:" & vbTab & EmployeeName & vbCrLf & "Hourly Salary:" & vbTab & FormatCurrency(HourlySalary) & vbCrLf &

Page 208: Microsoft Visual Basic 2010 Tutorial

5. Execute the application to test it

6. Close the form and the DOS window to return to your programming environment

The Do...Loop While Loop

The formula of the Do... Loop While loop is:

Do Statement(s)Loop While Condition

This compiler first executes the Statement or Statements. After executing the Statement(s)section, the compiler checks the Condition. If the Condition is true, then the compiler returns tothe Statement(s) and execute(s) it(them). The compiler keeps doing this check-executiongymnastic. As long as the Condition is true, the Statement(s) section will be executed and theCondition will be tested again. If the Condition is false or once the condition becomes false, thestatement will not be executed and the program will move on. Here is an example:

Module Exercise

Public Function Main() As Integer Dim Answer As String

Do Answer = InputBox("Are we there yet (1=Yes/0=No)? ") Loop While Answer <> "1"

MsgBox("Wonderful, we have arrived")

Return 0 End Function

End Module

Here is an example of running the program:

"Weekly Hours:" & vbTab & FormatNumber(WeeklyHours) & vbCrLf & "Regular Pay:" & vbTab & FormatCurrency(RegularPay) & vbCrLf & "Overtime Pay:" & vbTab & FormatCurrency(OvertimePay) & vbCrLf & "Total Pay:" & vbTab & FormatCurrency(NetPay) & vbCrLf & "======================"

MsgBox(Payroll, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") Return 0 End Function

End Module

Page 209: Microsoft Visual Basic 2010 Tutorial

As you may guess already, the Condition must provide a way for it to be true or to be false.Otherwise, the looping would be executed over and over again.

Practical Learning: Using Do...Loop While

1. To apply Do...Loop While condition, change the document as follows:

Module BethesdaCarRental

Public Function Main() As Integer Dim EmployeeName As String Dim StrHourlySalary As String, StrWeeklyHours As String Dim HourlySalary As Double Dim WeeklyHours As Double Dim RegularTime As Double, Overtime As Double Dim RegularPay As Double, OvertimePay As Double Dim NetPay As Double Dim Answer As String

Dim Payroll As String

Answer = "0" HourlySalary = "0.00" WeeklyHours = "0.00"

Do EmployeeName = InputBox("Enter Employee Name:", "Bethesda Car Rental", "John Doe")

StrHourlySalary = InputBox("Enter Employee Hourly Salary:", "Bethesda Car Rental", "0.00")

If IsNumeric(StrHourlySalary) Then HourlySalary = CDbl(StrHourlySalary) Else MsgBox("The number " & StrHourlySalary & " you entered " & "for the hourly salary is not valid", MsgBoxStyle.Exclamation Or MsgBoxStyle.Critical, "Bethesda Car Rental") End If

StrWeeklyHours = InputBox("Enter Employee Weekly Hours:", "Bethesda Car Rental", "0.00")

If IsNumeric(StrWeeklyHours) Then WeeklyHours = CDbl(StrWeeklyHours) Else MsgBox("The value " & StrWeeklyHours & " you provided " & "for the weekly hours is not valid", MsgBoxStyle.Exclamation Or MsgBoxStyle.Critical, "Bethesda Car Rental")

Page 210: Microsoft Visual Basic 2010 Tutorial

End If

If WeeklyHours < 40 Then RegularTime = WeeklyHours Overtime = 0 RegularPay = HourlySalary * RegularTime OvertimePay = 0 NetPay = RegularPay Else RegularTime = 40 Overtime = WeeklyHours - 40 RegularPay = HourlySalary * 40 OvertimePay = HourlySalary * Overtime NetPay = RegularPay + OvertimePay End If

Payroll = "======================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Employee Payroll =-=-==" & vbCrLf & "-------------------------------------------" & vbCrLf & "Employee Name:" & vbTab & EmployeeName & vbCrLf & "Hourly Salary:" & vbTab & FormatCurrency(HourlySalary) & vbCrLf & "Weekly Hours:" & vbTab & FormatNumber(WeeklyHours) & vbCrLf & "Regular Pay:" & vbTab & FormatCurrency(RegularPay) & vbCrLf & "Overtime Pay:" & vbTab & FormatCurrency(OvertimePay) & vbCrLf & "Total Pay:" & vbTab & FormatCurrency(NetPay) & vbCrLf & "======================"

MsgBox(Payroll, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental")

Answer = InputBox("Do you want to create another payroll (y=Yes/n=No)?") Loop While Answer.ToUpper() = "Y"

Return 0 End Function

End Module

2. Execute the application and create a payroll

3. When asked whether you want to create another payroll, enter y and create another payroll

4. When asked whether you want to create another payroll, enter y again and create anotherpayroll

5. When asked whether you want to create another payroll, enter q

6. Close the form and return to your programming environment

The Do...Loop Until Statement

An alternative to the Do... Loop While uses the following formula:

Do Statement(s)Loop Until Condition

Once again, the Statement(s) section executes first. After executing the Statement(s), thecompiler checks the Condition. If the Condition is true, the compiler returns to the Statement(s)section to execute it. This will continue until the Condition becomes false. Once the Conditionbecomes false, the compiler gets out of this loop and continues with the section under the LoopUntil line.

Here is an example:

Module Exercise

Public Function Main() As Integer Dim Answer As String

Do Answer = InputBox("Are we there yet (1=Yes/0=No)? ") Loop Until Answer = "1"

MsgBox("Wonderful, we have arrived")

Return 0 End Function

End Module

Practical Learning: Using a Do...Loop Until Statement

1. Create a new Console Application named BCR6

2. In the Solution Explorer, right-click Module1.vb and click Rename

3. Type BethesdaCarRental.vb and press Enter

Page 211: Microsoft Visual Basic 2010 Tutorial

4. Accept to change the name of the module and change the document as follows:

Module BethesdaCarRental Private Function GetEmployeeName(ByVal EmplNbr As Long) As String Dim Name As String

If EmplNbr = 22804 Then Name = "Helene Mukoko" ElseIf EmplNbr = 92746 Then Name = "Raymond Kouma" ElseIf EmplNbr = 54080 Then Name = "Henry Larson" ElseIf EmplNbr = 86285 Then Name = "Gertrude Monay" Else Name = "Unknown" End If

Return Name End Function

Public Function Main() As Integer Dim EmployeeNumber As Long, EmployeeName As String Dim CustomerName As String Dim TagNumber As String, CarSelected As String Dim CarStatus As Integer, CarCondition As String Dim Tank As Integer, TankLevel As String Dim RentStartDate As Date, RentEndDate As Date Dim NumberOfDays As Integer Dim RateType As String, RateApplied As Double Dim OrderTotal As Double Dim OrderInvoice As String Dim Answer As MsgBoxResult

RateType = "Weekly Rate" RateApplied = 0 OrderTotal = RateApplied

Do EmployeeNumber = CLng(InputBox("Employee number (who processed this order):", "Bethesda Car Rental", "00000"))

EmployeeName = GetEmployeeName(EmployeeNumber)

CustomerName = InputBox("Enter Customer Name:", "Bethesda Car Rental", "John Doe")

TagNumber = InputBox("Enter the tag number of the car to rent:", "Bethesda Car Rental", "000000")

CarSelected = Microsoft.VisualBasic.Switch( TagNumber = "297419", "BMW 335i", TagNumber = "485M270", "Chevrolet Avalanche", TagNumber = "247597", "Honda Accord LX", TagNumber = "924095", "Mazda Miata", TagNumber = "772475", "Chevrolet Aveo", TagNumber = "M931429", "Ford E150XL", TagNumber = "240759", "Buick Lacrosse", True, "Unidentified Car")

CarStatus = CInt(InputBox("After inpecting it, enter car condition:" & vbCrLf & "1. Excellent - No scratch, no damage, no concern" & vbCrLf & "2. Good - Some concerns (scratches or missing something)." & "Make sure the customer is aware." & vbCrLf & "3. Drivable - The car is good enough to drive." & "The customer must know the status of the car " & "and agree to rent it", "Bethesda Car Rental", 1))

Select Case CarStatus Case 1 CarCondition = "Excellent" Case 2 CarCondition = "Good" Case 3 CarCondition = "Drivable" Case Else CarCondition = "Unknown" End Select

Tank = CInt(InputBox("Enter Tank Level:" & vbCrLf & "1. Empty" & vbCrLf & "2. 1/4 Empty" & vbCrLf & "3. 1/2 Full" & vbCrLf & "4. 3/4 Full" & vbCrLf & "5. Full", "Bethesda Car Rental", 1)) TankLevel = Choose(Tank, "Empty", "1/4 Empty", "1/2 Full", "3/4 Full", "Full")

RentStartDate = CDate(InputBox("Enter Rent Start Date:", "Bethesda Car Rental", #1/1/1900#)) RentEndDate = CDate(InputBox("Enter Rend End Date:", "Bethesda Car Rental", #1/1/1900#))

Page 212: Microsoft Visual Basic 2010 Tutorial

5. Execute the application

6. Enter the employee number as 92746, the customer name as James Wiley, the tag numberas 297419, the car condition as 1, the tank level as 5, the start date as 11/07/2008, theend date as 11/10/2008, and the rate applied 49.95

NumberOfDays = DateDiff(DateInterval.Day, RentStartDate, RentEndDate)

RateApplied = CDbl(InputBox("Enter Rate Applied:", "Bethesda Car Rental", 0))

Dim TemporaryRate As Double

Select Case NumberOfDays Case 0, 1 RateType = "Daily Rate" OrderTotal = RateApplied Case 2 RateType = "Weekend Rate" TemporaryRate = RateApplied * 50 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * 2 Case 2 To 7 RateType = "Weekly Rate" TemporaryRate = RateApplied * 25 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * NumberOfDays Case Is > 8 RateType = "Monthly Rate" TemporaryRate = RateApplied * 15 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * NumberOfDays End Select

OrderInvoice = "===========================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Order Processing =-=-==" & vbCrLf & "------------------------------------------------" & vbCrLf & "Processed by:" & vbTab & EmployeeName & vbCrLf & "Processed for:" & vbTab & CustomerName & vbCrLf & "------------------------------------------------" & vbCrLf & "Car Selected:" & vbCrLf & _ vbTab & "Tag #:" & vbTab & TagNumber & vbCrLf & vbTab & "Car:" & vbTab & CarSelected & vbCrLf & vbTab & "Tank:" & vbTab & TankLevel & vbCrLf & "Car Condition:" & vbTab & CarCondition & vbCrLf & "------------------------------------------------" & vbCrLf & "Start Date:" & vbTab & RentStartDate & vbCrLf & "End Date:" & vbTab & RentEndDate & vbCrLf & "Nbr of Days:" & vbTab & NumberOfDays & vbCrLf & "------------------------------------------------" & vbCrLf & "Rate Type:" & vbTab & RateType & vbCrLf & _ "Rate Applied:" & vbTab & FormatCurrency(RateApplied) & vbCrLf & "Order Total:" & vbTab & FormatCurrency(OrderTotal) & vbCrLf & "==========================="

MsgBox(OrderInvoice, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental")

Answer = MsgBox("Do you want to process another order?", MsgBoxStyle.Information Or MsgBoxStyle.YesNo, "Bethesda Car Rental") Loop Until Answer = MsgBoxResult.No Return 0 End Function

End Module

Page 213: Microsoft Visual Basic 2010 Tutorial

7. When asked whether you want to process another order, click Yes

8. Enter the employee number as 54080, the customer name as Sunil Ajat, the tag number as240759, the car condition as 3, the tank level as 3, the start date as 11/05/2008, the enddate as 11/15/2008, and the rate applied 70.25

9. When asked whether you want to process another order, click Yes

10. Enter the employee number as 22804, the customer name as George Livingstone, the tagnumber as 924095, the car condition as 2, the tank level as 4, the start date as09/15/2008, the end date as 09/19/2008, and the rate applied 65.75

11. When asked whether you want to process another order, click Yes

12. Enter the employee number as 86285, the customer name as Antoinette D. Liel, the tagnumber as 485M270, the car condition as 2, the tank level as 2, the start date as11/15/2008, the end date as 11/17/2008, and the rate applied 55.50

13. When asked whether you want to process another order, click No

14. Close the message box and the DOS window to return to your programming environment

The Do While... Loop Statement

As mentioned above, the Do While... Loop expression executes a statement first before checkinga condition that would allow it to repeat. If you want to check a condition first before executing astatement, you can use another version as Do While... Loop. Its formula is:

Do While Condition Statement(s)Loop

In this case, the compiler checks the Condition first. If the Condition is true, the compiler then

Page 214: Microsoft Visual Basic 2010 Tutorial

executes the Statement(s) and checks the Condition again. If the Condition is false, or when theCondition becomes false, the compiler skips the Statement(s) section and continues with the codebelow the Loop keyword.

Here is an example:

Module Exercise

Public Function Main() As Integer Dim Number As Short

Do While Number < 46 Number += CShort(InputBox("Enter a number")) Loop

MsgBox("Counting Stopped at: " & Number) Return 0 End Function

End Module

The Do Until... Loop Statement

An alternative to the Do While... Loop loop uses the following formula:

Do Until Condition Statement(s)Loop

This loop works like the Do While... Loop expression. The compiler examines the Condition first.If the condition is true, then it executes the Statement(s) section.

Here is an example:

Module Exercise

Public Function Main() As Integer Dim Answer As String Answer = "0"

Do Until Answer = "1" Answer = InputBox("Are we there yet (1=Yes/0=No)? ") Loop

MsgBox("Wonderful, we have arrived") Return 0 End Function

End Module

Loop Counters

Introduction

The looping statements we reviewed above are used when you don't know or can't anticipate thenumber of times a condition needs to be checked in order to execute a statement. If you knowwith certainty how many times you want to execute a statement, you can use another form ofloops that use the For...Next expression.

The For...To...Next Loop

One of the loop counters you can use is For...To...Next. Its formula is:

For Counter = Start To End Statement(s)Next

Used for counting, the expression begins counting at the Start point. Then it examines whetherthe current value (after starting to count) is lower than End. If that's the case, it then executesthe Statement(s). Next, it increments the value of Counter by 1 and examines the condition again.This process goes on until the value of Counter becomes equal to the End value. Once thiscondition is reached, the looping stops.

Here is an example:

Module Exercise

Public Function Main() As Integer Dim Number As Short

For Number = 5 To 16 MsgBox(Number) Next

MsgBox("Counting Stopped at: " & Number) Return 0 End Function

Page 215: Microsoft Visual Basic 2010 Tutorial

End Module

Stepping the Counting Loop

The formula above will increment the counting by 1 at the end of each statement. If you want tocontrol how the incrementing processes, you can set your own, using the Step option. Here is theformula:

For Counter = Start To End Step Increment Statement(s)Next

You can set the incrementing value to your choice. If the value of Increment is positive, theCounter will be added its value. Here is an example:

Module Exercise

Public Function Main() As Integer Dim Number As Short

For Number = 5 To 42 Step 4 MsgBox(Number) Next

MsgBox("Counting Stopped at: " & Number) Return 0 End Function

End Module

You can also set a negative value to the Increment factor, in which case the Counter will besubtracted the set value.

Previous Copyright © 2008-2010 FunctionX, Inc. Next

Page 216: Microsoft Visual Basic 2010 Tutorial

Managing Conditional Statements

Fundamentals of Managing Conditional Statements

Conditional Nesting

We know how to create normal conditional statements and loops. Here is an example:

Module Exercise

Private Sub RequestNumber() Dim Number%

Number% = InputBox("Enter a number that is lower than 5")

If Number% <= 5 Then MsgBox(Number%) End If

End Sub

Public Function Main() As Integer RequestNumber() Return 0 End Function

End Module

When this program runs, if the user enter a number lower than 5 (included), a message box woulddisplay that number. If the user enter a number higher than 5, the program would end but wouldnot display it. In a typical program, after validating a condition, you may want to take action. Todo that, you can create a section of program inside the validating conditional statement. In fact,you can create a conditional statement inside of another conditional statement. This is referred toas nesting a condition. Any condition can be nested in another and multiple conditions can beincluded inside of another.

Here is an example where an If...Then condition is nested inside of a Do...Loop While loop:

Module Exercise

Private Sub RequestNumber() Dim Number%

Do Number% = InputBox("Enter a number that is lower than 5")

If Number% <= 5 Then MsgBox(Number%) End If Loop While Number <= 5 End Sub

Public Function Main() As Integer RequestNumber() Return 0 End Function

End Module

When the program runs, it asks the user to provide a number lower than 5 (included). If the userprovides such a number, the value of the number is displayed and the user is asked to provideanother number. This would continue as long as the user is entering a number lower than 5.Otherwise, the program would stop.

Practical Learning: Nesting Conditions

1. Start Microsoft Visual Basic and create a Console Application named BCR7 (or open the BCR6application from the previous lesson and go to the next section)

2. In the Solution Explorer, right-click Module1.vb and click Rename

3. Type BethesdaCarRental.vb and press Enter

4. Change the document as follows:

Module BethesdaCarRental Private Function GetEmployeeName(ByVal EmplNbr As Long) As String Dim Name As String

If EmplNbr = 22804 Then

Page 217: Microsoft Visual Basic 2010 Tutorial

Name = "Helene Mukoko" ElseIf EmplNbr = 92746 Then Name = "Raymond Kouma" ElseIf EmplNbr = 54080 Then Name = "Henry Larson" ElseIf EmplNbr = 86285 Then Name = "Gertrude Monay" Else Name = "Unknown" End If

Return Name End Function

Public Function Main() As Integer Dim EmployeeNumber As Long, EmployeeName As String Dim CustomerName As String Dim TagNumber As String, CarSelected As String Dim RentStartDate As Date, RentEndDate As Date Dim NumberOfDays As Integer Dim RateType As String, RateApplied As Double Dim OrderTotal As Double Dim OrderInvoice As String Dim Answer As MsgBoxResult

RateType = "Weekly Rate" RateApplied = 0 OrderTotal = RateApplied

Do EmployeeNumber = CLng(InputBox("Employee number (who processed this order):", "Bethesda Car Rental", "00000"))

EmployeeName = GetEmployeeName(EmployeeNumber)

CustomerName = InputBox("Enter Customer Name:", "Bethesda Car Rental", "John Doe")

TagNumber = InputBox("Enter the tag number of the car to rent:", "Bethesda Car Rental", "000000")

CarSelected = Microsoft.VisualBasic.Switch( TagNumber = "297419", "BMW 335i", TagNumber = "485M270", "Chevrolet Avalanche", TagNumber = "247597", "Honda Accord LX", TagNumber = "924095", "Mazda Miata", TagNumber = "772475", "Chevrolet Aveo", TagNumber = "M931429", "Ford E150XL", TagNumber = "240759", "Buick Lacrosse", True, "Unidentified Car")

RentStartDate = CDate(InputBox("Enter Rent Start Date:", "Bethesda Car Rental", #1/1/1900#)) RentEndDate = CDate(InputBox("Enter Rend End Date:", "Bethesda Car Rental", #1/1/1900#)) NumberOfDays = DateDiff(DateInterval.Day, RentStartDate, RentEndDate)

RateApplied = CDbl(InputBox("Enter Rate Applied:", _ "Bethesda Car Rental", 0))

Dim TemporaryRate As Double

Select Case NumberOfDays Case 0, 1 RateType = "Daily Rate" OrderTotal = RateApplied Case 2 RateType = "Weekend Rate" TemporaryRate = RateApplied * 50 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * 2 Case 2 To 7 RateType = "Weekly Rate" TemporaryRate = RateApplied * 25 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * NumberOfDays Case Is > 8 RateType = "Monthly Rate" TemporaryRate = RateApplied * 15 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * NumberOfDays End Select

OrderInvoice = "===========================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Order Processing =-=-==" & vbCrLf & "------------------------------------------------" & vbCrLf & "Processed by:" & vbTab & EmployeeName & vbCrLf & "Processed for:" & vbTab & CustomerName & vbCrLf & "------------------------------------------------" & vbCrLf & "Car Selected:" & vbCrLf & vbTab & "Tag #:" & vbTab & TagNumber & vbCrLf & vbTab & "Car:" & vbTab & CarSelected & vbCrLf & "------------------------------------------------" & vbCrLf & "Start Date:" & vbTab & RentStartDate & vbCrLf & "End Date:" & vbTab & RentEndDate & vbCrLf & "Nbr of Days:" & vbTab & NumberOfDays & vbCrLf & "------------------------------------------------" & vbCrLf & "Rate Type:" & vbTab & RateType & vbCrLf & "Rate Applied:" & vbTab & FormatCurrency(RateApplied) & vbCrLf &

Page 218: Microsoft Visual Basic 2010 Tutorial

5. Execute the application

6. Enter the employee number as 92746, the customer name as James Wiley, the tag numberas 297419, the car condition as 1, the tank level as 5, the start date as 10/22/2008, theend date as 11/07/2008, and the rate applied 49.95

7. When asked whether you want to process another order, click No

8. Close the message box and the DOS window to return to your programming environment

The Goto Statement

The Goto statement allows a program execution to jump to another section of a procedure inwhich it is being used. In order to use the Goto statement, insert a name on a particular sectionof your procedure so you can refer to that name. The name, also called a label, is made of oneword and follows the rules we have applied to names (the name can be anything), then followedby a colon ":".

The following program uses a For loop to count from 2 to 18, but when it encounters 10, it jumpsto a designated section of the program:

Module Exercise

Public Function Main() As Integer Dim i As Integer

For i = 2 To 18 Step 1 If i = 10 Then GoTo StoppingHere End If MsgBox("Value: " & i) Next

StoppingHere: MsgBox("The execution jumped here.") Return 0 End Function

End Module

This would produce:

In the same way, you can create as many labels as you judge them necessary in your code andrefer to them when you want. Here is an example with various labels:

Module Exercise

Public Function Main() As Integer Dim Answer As Byte

"Order Total:" & vbTab & FormatCurrency(OrderTotal) & vbCrLf & "==========================="

MsgBox(OrderInvoice, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental")

Answer = MsgBox("Do you want to process another order?", MsgBoxStyle.Information Or MsgBoxStyle.YesNo, "Bethesda Car Rental") Loop Until Answer = MsgBoxResult.No Return 0 End Function

End Module

Page 219: Microsoft Visual Basic 2010 Tutorial

Answer = InputBox(" -=- Multiple Choice Question -=-" & vbCrLf & "To create a constant in your code, " & "you can use the Constant keyword" & vbCrLf & "Your choice (1=True/2=False)? ")

If Answer = 1 Then GoTo Wrong If Answer = 2 Then GoTo Right

Wrong: MsgBox("Wrong: The keyword used to create a constant is Const") GoTo Leaving

Right: MsgBox("Right: Constant is not a keyword")

Leaving: Return 0 End Function

End Module

Here is an example of executing the program with Answer = 1:

Here is another example of executing the same program with Answer = 2:

Practical Learning: Going To a Label

1. To go to a label, change the document as follows:

Module BethesdaCarRental Private Function GetEmployeeName(ByVal EmplNbr As Long) As String Dim Name As String

If EmplNbr = 22804 Then Name = "Helene Mukoko" ElseIf EmplNbr = 92746 Then Name = "Raymond Kouma" ElseIf EmplNbr = 54080 Then Name = "Henry Larson" ElseIf EmplNbr = 86285 Then Name = "Gertrude Monay" Else Name = "Unknown" End If

Return Name End Function

Public Function Main() As Integer Dim EmployeeNumber As Long, EmployeeName As String Dim CustomerName As String Dim TagNumber As String, CarSelected As String Dim RentStartDate As Date, RentEndDate As Date Dim NumberOfDays As Integer Dim RateType As String, RateApplied As Double

Page 220: Microsoft Visual Basic 2010 Tutorial

Dim OrderTotal As Double Dim OrderInvoice As String Dim Answer As MsgBoxResult

RateType = "Weekly Rate" RateApplied = 0 OrderTotal = RateApplied

Do EmployeeNumber = CLng(InputBox("Employee number (who processed this order):", _ "Bethesda Car Rental", "00000"))

EmployeeName = GetEmployeeName(EmployeeNumber)

CustomerName = InputBox("Enter Customer Name:", "Bethesda Car Rental", "John Doe")

TagNumber = InputBox("Enter the tag number of the car to rent:", _ "Bethesda Car Rental", "000000")

CarSelected = Microsoft.VisualBasic.Switch( TagNumber = "297419", "BMW 335i", TagNumber = "485M270", "Chevrolet Avalanche", TagNumber = "247597", "Honda Accord LX", TagNumber = "924095", "Mazda Miata", TagNumber = "772475", "Chevrolet Aveo", TagNumber = "M931429", "Ford E150XL", TagNumber = "240759", "Buick Lacrosse", True, "Unidentified Car")

RentStartDate = CDate(InputBox("Enter Rent Start Date:", "Bethesda Car Rental", #1/1/1900#)) RentEndDate = CDate(InputBox("Enter Rend End Date:", "Bethesda Car Rental", #1/1/1900#))

If RentEndDate < RentStartDate Then MsgBox("The values you entered for the start and end dates " & "are not consecute. The rent start date must occur " & "prior to the rent end date", MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") GoTo RestartOrderProcessing End If

NumberOfDays = DateDiff(DateInterval.Day, RentStartDate, RentEndDate)

RateApplied = CDbl(InputBox("Enter Rate Applied:", "Bethesda Car Rental", 0))

Dim TemporaryRate As Double

Select Case NumberOfDays Case 0, 1 RateType = "Daily Rate" OrderTotal = RateApplied Case 2 RateType = "Weekend Rate" TemporaryRate = RateApplied * 50 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * 2 Case 2 To 7 RateType = "Weekly Rate" TemporaryRate = RateApplied * 25 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * NumberOfDays Case Is > 8 RateType = "Monthly Rate" TemporaryRate = RateApplied * 15 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * NumberOfDays End Select

OrderInvoice = "===========================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Order Processing =-=-==" & vbCrLf & "------------------------------------------------" & vbCrLf & "Processed by:" & vbTab & EmployeeName & vbCrLf & "Processed for:" & vbTab & CustomerName & vbCrLf & "------------------------------------------------" & vbCrLf & "Car Selected:" & vbCrLf & vbTab & "Tag #:" & vbTab & TagNumber & vbCrLf & vbTab & "Car:" & vbTab & CarSelected & vbCrLf & "------------------------------------------------" & vbCrLf & "Start Date:" & vbTab & RentStartDate & vbCrLf & "End Date:" & vbTab & RentEndDate & vbCrLf & "Nbr of Days:" & vbTab & NumberOfDays & vbCrLf & "------------------------------------------------" & vbCrLf & "Rate Type:" & vbTab & RateType & vbCrLf & "Rate Applied:" & vbTab & FormatCurrency(RateApplied) & vbCrLf & "Order Total:" & vbTab & FormatCurrency(OrderTotal) & vbCrLf & "==========================="

MsgBox(OrderInvoice, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental")

RestartOrderProcessing: Answer = MsgBox("Do you want to process another order?", MsgBoxStyle.Information Or MsgBoxStyle.YesNo, "Bethesda Car Rental")

Page 221: Microsoft Visual Basic 2010 Tutorial

2. Execute the application

3. Enter the employee number as 92746, the customer name as James Wiley, the tag numberas 297419, the car condition as 1, the tank level as 5, the start date as 10/22/2008, theend date as 11/07/2008, and the rate applied 49.95

4. When asked whether you want to process another order, click Yes

5. Enter the employee number as 92746, the customer name as James Wiley, the tag numberas 297419, the car condition as 1, the tank level as 5, the start date as 11/07/2008, theend date as 11/10/2008, and the rate applied 49.95

6. When asked whether you want to process another order, click No

7. Close the message box and the DOS window to return to your programming environment

Negating a Conditional Statement

So far, we have learned to write a conditional statement that is true or false. You can reverse thetrue (or false) value of a condition by making it false (or true). To support this operation, theVisual Basic language provides an operator called Not. Its formula is:

Not Expression

When writing the statement, type Not followed by a logical expression. The expression can be asimple Boolean expression. Here is an example:

Module Exercise

Public Function Main() As Integer Dim IsMarried As Boolean

MsgBox("Is Married: " & IsMarried) MsgBox("Is Married: " & Not IsMarried)

Return 0 End Function

End Module

This would produce:

In this case, the Not operator is used to change the logical value of the variable. When a Booleanvariable has been "notted", its logical value has changed. If the logical value was True, it wouldbe changed to False and vice versa. Therefore, you can inverse the logical value of a Booleanvariable by "notting" or not "notting" it.

Now consider the following program we saw in Lesson 11:

Module Exercise

Public Function Main() As Integer Dim IsMarried As Boolean Dim TaxRate As Double

TaxRate = 33.0

MsgBox("Tax Rate: " & TaxRate & "%")

IsMarried = True If IsMarried = True Then TaxRate = 30.65

MsgBox("Tax Rate: " & TaxRate & "%") End If

Return 0 End Function

End Module

Loop Until Answer = MsgBoxResult.No Return 0 End Function

End Module

Page 222: Microsoft Visual Basic 2010 Tutorial

This would produce:

Probably the most classic way of using the Not operator consists of reversing a logical expression.To do this, you precede the logical expression with the Not operator. Here is an example:

Module Exercise

Public Function Main() As Integer Dim IsMarried As Boolean Dim TaxRate As Double

TaxRate = 33.0

MsgBox("Tax Rate: " & TaxRate & "%")

IsMarried = True If Not IsMarried Then TaxRate = 30.65

MsgBox("Tax Rate: " & TaxRate & "%") End If

Return 0 End Function

End Module

This would produce:

In the same way, you can negate any logical expression.

Exiting a Procedure or a Loop

Exiting a Procedure

In the conditional statements and loops we have created so far, we assumed that the wholecondition would be processed. Here is an example:

Module Exercise

Private Sub ShowNumbers() Dim Number As Short

For Number = 1 To 6 MsgBox(Number) Next

End Sub

Public Function Main() As Integer ShowNumbers() Return 0 End Function

End Module

This would produce:

Page 223: Microsoft Visual Basic 2010 Tutorial

In some cases, you may want to exit a conditional statement or a loop before its end. To assistwith with this, the Visual Basic language provides the Exit keyword. This keyword works like anoperator. It can be applied to a procedure or a For loop. Consider the following ShowNamesprocedure:

Module Exercise

Private Sub ShowNames() MsgBox("Patricia Katts") MsgBox("Gertrude Monay") MsgBox("Hermine Nkolo") MsgBox("Paul Bertrand Yamaguchi") End Sub

Public Function Main() As Integer ShowNames() Return 0 End Function

End Module

When the procedure is called, it displays four message boxes that each shows a name. Imaginethat at some point you want to ask the compiler to stop in the middle of a procedure. To do this,in the section where you want to stop the flow of a procedure, type Exit Sub. Here is an example:

Module Exercise

Private Sub ShowNames() MsgBox("Patricia Katts") MsgBox("Gertrude Monay") Exit Sub MsgBox("Hermine Nkolo") MsgBox("Paul Bertrand Yamaguchi") End Sub

Public Function Main() As Integer ShowNames() Return 0 End Function

End Module

This time, when the program runs, the ShowNames procedure would be accessed and would startdisplaying the message boxes. After displaying two, the Exit Sub would ask the compiler to stopand get out of the procedure.

Because a function is just a type of procedure that is meant to return a value, you can use theExit keyword to get out of a function before the End Function line. To do this, in the sectionwhere you want to stop the flow of the function, type Exit Function.

Exiting a For Loop Counter

You can also exit a For loop. To do this, in the section where you want to stop, type Exit For.Here is an example to stop a continuing For loop:

Module Exercise

Private Sub ShowNumbers() Dim Number As Short

For Number = 1 To 6 MsgBox(Number) If Number = 4 Then Exit For End If Next

End Sub

Public Function Main() As Integer ShowNumbers() Return 0 End Function

End Module

When this program executes, it is supposed to display numbers from 1 to 6, but an If...Thencondition states that if it gets to the point where the number is 4, it should stop. If you use anExit For statement, the compiler would stop the flow of For and continue with code after the Nextkeyword.

Exiting a Do Loop

Page 224: Microsoft Visual Basic 2010 Tutorial

You can also use the Exit operator to get out of a Do loop. To do this, inside of a Do loop whereyou want to stop, type Exit Do.

Logical Conjunction

Introduction

As mentioned already, you can nest one conditional statement inside of another. To illustrate,imagine you create a program that would be used by a real estate company that sells houses. Youmay face a customer who wants to purchase a single family house but the house should not costover $550,001. To implement this scenario, you can first write a program that asks the user toselect a type of house and then a conditional statement would check the type of house. Here is anexample:

Module Exercise

Public Function Main() As Integer Dim Type As String Dim Choice As Integer Dim Value As Double Type = "Unknown"

Choice = CInt(InputBox("Enter the type of house you want to purchase" & vbCrLf & "1. Single Family" & vbCrLf & "2. Townhouse" & vbCrLf & "3. Condominium" & vbCrLf & vbCrLf & "You Choice? ")) Value = CDbl(InputBox("Up to how much can you afford?"))

Type = Choose(Choice, "Single Family", "Townhouse", "Condominium")

Return 0 End Function

End Module

If the user selects a single family, you can then write code inside the conditional statement of thesingle family. Here is an example:

Module Exercise

Public Function Main() As Integer Dim Type As String Dim Choice As Integer Dim Value As Double Type = "Unknown"

Choice = CInt(InputBox("Enter the type of house you want to purchase" & vbCrLf & "1. Single Family" & vbCrLf & "2. Townhouse" & vbCrLf & "3. Condominium" & vbCrLf & vbCrLf & "You Choice? ")) Value = CDbl(InputBox("Up to how much can you afford?"))

Type = Choose(Choice, "Single Family", "Townhouse", "Condominium")

If Choice = 1 Then MsgBox("Desired House Type: " & vbTab & Type & vbCrLf & "Maximum value afforded: " & vbTab & FormatCurrency(Value)) End If

Return 0 End Function

End Module

In that section, you can then write code that would request and check the value the user entered.If that value is valid, you can take necessary action. Here is an example:

Module Exercise

Public Function Main() As Integer Dim Type As String Dim Choice As Integer Dim Value As Double Type = "Unknown"

Choice = CInt(InputBox("Enter the type of house you want to purchase" & vbCrLf & "1. Single Family" & vbCrLf & "2. Townhouse" & vbCrLf & "3. Condominium" & vbCrLf & vbCrLf & "You Choice? ")) Value = CDbl(InputBox("Up to how much can you afford?"))

Page 225: Microsoft Visual Basic 2010 Tutorial

Type = Choose(Choice, "Single Family", "Townhouse", "Condominium")

If Choice = 1 Then MsgBox("Desired House Type: " & vbTab & Type & vbCrLf & "Maximum value afforded: " & vbTab & FormatCurrency(Value)) If Value <= 550000 Then MsgBox("Desired House Matched") Else MsgBox("The House Doesn't Match the Desired Criteria") End If End If

Return 0 End Function

End Module

A Conditional Conjunction

Using conditional nesting, we have seen how you can write one conditional that depends onanother. But you must write one first condition, check it, then nest the other condition. This worksfine and there is nothing against it. To provide with with an alternative, you can use what isreferred to as a logical conjunction. It consists of writing one If...Then expression that checks twoconditions at the same time. To illustrate, once again consider a customer who wants to purchasea single family home that is less than $550,000. You can consider two statements as follows:

1. The house is single family

2. The house costs less than $550,000

To implement it, you would need to write an If...Then condition as:

If The house is single family AND The house costs less than $550,000 Then

Validate

End If

In the Visual Basic language, the operator used to perform a logical conjunction is And. Here is anexample of using it:

Module Exercise

Public Function Main() As Integer Dim Type As String Dim Choice As Integer Dim Value As Double

Type = "Unknown"

Choice = _ CInt(InputBox("Enter the type of house you want to purchase" & vbCrLf & "1. Single Family" & vbCrLf & "2. Townhouse" & vbCrLf & "3. Condominium" & vbCrLf & vbCrLf & "You Choice? ")) Value = CDbl(InputBox("Up to how much can you afford?"))

Type = Choose(Choice, "Single Family", "Townhouse", "Condominium")

If Type = "Single Family" And Value <= 550000 Then MsgBox("Desired House Type: " & vbTab & Type & vbCrLf & "Maximum value afforded: " & vbTab & FormatCurrency(Value)) MsgBox("Desired House Matched") Else MsgBox("The House Doesn't Match the Desired Criteria") End If

Return 0 End Function

End Module

By definition, a logical conjunction combines two conditions. To make the program easier to read,each side of the conditions can be included in parentheses. Here is an example:

Module Exercise

Public Function Main() As Integer . . . No Change

If (Type = "Single Family") And (Value <= 550000) Then MsgBox("Desired House Type: " & vbTab & Type & vbCrLf & "Maximum value afforded: " & vbTab & FormatCurrency(Value)) MsgBox("Desired House Matched") Else MsgBox("The House Doesn't Match the Desired Criteria") End If

Return 0

Page 226: Microsoft Visual Basic 2010 Tutorial

End Function

End Module

To understand how logical conjunction works, from a list of real estate properties, after selectingthe house type, if you find a house that is a single family home, you put it in the list of consideredproperties:

Type of House House

The house is single family True

If you find a house that is less than or equal to $550,000, you retain it:

Price Range Value

$550,000 True

For the current customer, you want a house to meet BOTH criteria. If the house is a town house,based on the request of our customer, its conditional value is false. If the house is less than$550,000, such as $485,000, the value of the Boolean Value is true:

If the house is a town house, based on the request of our customer, its conditional value is false.If the house is more than $550,000, the value of the Boolean Value is true. In logical conjunction,if one of the conditions is false, the result if false also. This can be illustrated as follows:

Type of House House Value Result

Town House $625,000 Town House AND $625,000

False False False

Suppose we find a single family home. The first condition is true for our customer. With the ANDBoolean operator, if the first condition is true, then we consider the second criterion. Suppose thatthe house we are considering costs $750,500: the price is out of the customer's range. Therefore,the second condition is false. In the AND Boolean algebra, if the second condition is false, even ifthe first is true, the whole condition is false. This would produce the following table:

Type of House House Value Result

Single Family $750,500 Single Family AND $750,500

True False False

Page 227: Microsoft Visual Basic 2010 Tutorial

Suppose we find a townhouse that costs $420,000. Although the second condition is true, the firstis false. In Boolean algebra, an AND operation is false if either condition is false:

Type of House House Value Result

Town House $420,000 Town House AND $420,000

False True False

If we find a single family home that costs $345,000, both conditions are true. In Boolean algebra,an AND operation is true if BOTH conditions are true. This can be illustrated as follows:

Type of House House Value Result

Single Family $345,000 Single Family AND $345,000

True True True

These four tables can be resumed as follows:

If Condition1 is If Condition2 isCondition1

ANDCondition2

False False False

False True False

True False False

True True True

As you can see, a logical conjunction is true only of BOTH conditions are true.

Practical Learning: Using a Logical Conjunction

1. Start Microsoft Visual Basic and create a Console Application named BCR7 (or open the BCR6application from the previous lesson and go to the next section)

2. In the Solution Explorer, right-click Module1.vb and click Rename

3. Type BethesdaCarRental.vb and press Enter

4. Change the document as follows:

Module BethesdaCarRental Private Function GetEmployeeName(ByVal EmplNbr As Long) As String Dim Name As String

If EmplNbr = 22804 Then Name = "Helene Mukoko" ElseIf EmplNbr = 92746 Then Name = "Raymond Kouma" ElseIf EmplNbr = 54080 Then Name = "Henry Larson" ElseIf EmplNbr = 86285 Then Name = "Gertrude Monay" Else Name = "Unknown" End If

Return Name End Function

Private Function GetCarCondition() As String Dim Status As Integer Dim Condition As String

Do Status = CInt(InputBox( _ "After inpecting it, enter car condition:" & vbCrLf & "1. Excellent - No scratch, no damage, no concern" & vbCrLf & "2. Good - Some concerns (scratches or missing something)." & "Make sure the customer is aware." & vbCrLf & "3. Drivable - The car is good enough to drive." & "The customer must know the status of the car " & "and agree to rent it", "Bethesda Car Rental", 1))

Select Case Status Case 1 Condition = "Excellent" Case 2 Condition = "Good" Case 3 Condition = "Drivable" Case Else Condition = "Unknown" End Select

Loop Until (Status > 0) And (Status < 4)

Return Condition End Function

Page 228: Microsoft Visual Basic 2010 Tutorial

Public Function Main() As Integer Dim EmployeeNumber As Long, EmployeeName As String Dim CustomerName As String Dim TagNumber As String, CarSelected As String Dim CarCondition As String Dim RentStartDate As Date, RentEndDate As Date Dim NumberOfDays As Integer Dim RateType As String, RateApplied As Double Dim OrderTotal As Double Dim OrderInvoice As String Dim Answer As MsgBoxResult

RateType = "Weekly Rate" RateApplied = 0 OrderTotal = RateApplied

Do EmployeeNumber = CLng(InputBox("Employee number (who processed this order):", "Bethesda Car Rental", "00000"))

EmployeeName = GetEmployeeName(EmployeeNumber)

CustomerName = InputBox("Enter Customer Name:", "Bethesda Car Rental", "John Doe")

TagNumber = InputBox("Enter the tag number of the car to rent:", "Bethesda Car Rental", "000000")

CarSelected = Microsoft.VisualBasic.Switch( TagNumber = "297419", "BMW 335i", TagNumber = "485M270", "Chevrolet Avalanche", TagNumber = "247597", "Honda Accord LX", TagNumber = "924095", "Mazda Miata", TagNumber = "772475", "Chevrolet Aveo", TagNumber = "M931429", "Ford E150XL", TagNumber = "240759", "Buick Lacrosse", True, "Unidentified Car")

CarCondition = GetCarCondition()

RentStartDate = CDate(InputBox("Enter Rent Start Date:", "Bethesda Car Rental", #1/1/1900#)) RentEndDate = CDate(InputBox("Enter Rend End Date:", "Bethesda Car Rental", #1/1/1900#))

If RentEndDate < RentStartDate Then MsgBox("The values you entered for the start and end dates " & "are not consecute. The rent start date must occur " & "prior to the rent end date", MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") GoTo RestartOrderProcessing End If NumberOfDays = DateDiff(DateInterval.Day, RentStartDate, RentEndDate)

RateApplied = CDbl(InputBox("Enter Rate Applied:", "Bethesda Car Rental", 0))

Dim TemporaryRate As Double

Select Case NumberOfDays Case 0, 1 RateType = "Daily Rate" OrderTotal = RateApplied Case 2 RateType = "Weekend Rate" TemporaryRate = RateApplied * 50 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * 2 Case 2 To 7 RateType = "Weekly Rate" TemporaryRate = RateApplied * 25 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * NumberOfDays Case Is > 8 RateType = "Monthly Rate" TemporaryRate = RateApplied * 15 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * NumberOfDays End Select

OrderInvoice = "===========================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Order Processing =-=-==" & vbCrLf & "------------------------------------------------" & vbCrLf & "Processed by:" & vbTab & EmployeeName & vbCrLf & "Processed for:" & vbTab & CustomerName & vbCrLf & "------------------------------------------------" & vbCrLf & "Car Selected:" & vbCrLf & vbTab & "Tag #:" & vbTab & TagNumber & vbCrLf & vbTab & "Car:" & vbTab & CarSelected & vbCrLf & "Car Condition:" & vbTab & CarCondition & vbCrLf & "------------------------------------------------" & vbCrLf & "Start Date:" & vbTab & RentStartDate & vbCrLf & "End Date:" & vbTab & RentEndDate & vbCrLf & "Nbr of Days:" & vbTab & NumberOfDays & vbCrLf & "------------------------------------------------" & vbCrLf & "Rate Type:" & vbTab & RateType & vbCrLf & "Rate Applied:" & vbTab & FormatCurrency(RateApplied) & vbCrLf &

Page 229: Microsoft Visual Basic 2010 Tutorial

5. Execute the application

6. Enter the employee number as 92746, the customer name as James Wiley, the tag numberas 297419, and the car condition as -5 and click OK

7. Enter the car condition as 8tank level as 5 and press Enter

8. Enter the car condition as 2, the start date as 11/07/2008, the end date as 11/10/2008,and the rate applied 49.95

9. When asked whether you want to process another order, click Yes

10. Enter the employee number as 54080, the customer name as Sunil Ajat, the tag number as240759, the car condition as 3, the tank level as 3, the start date as 11/05/2008, the enddate as 11/15/2008, and the rate applied 70.25

11. When asked whether you want to process another order, click No

12. Close the message box and the DOS window to return to your programming environment

Combining Conjunctions

As seen above, the logical conjunction operator is used to combine two conditions. In some cases,you will need to combine more than two conditions. Imagine a customer wants to purchase asingle family house that costs up to $450,000 with an indoor garage. This means that the housemust fulfill these three requirements:

A. The house is a single family home

B. The house costs less than $450,001

C. The house has an indoor garage

Here the program that could be used to check these conditions:

Module Exercise

Public Function Main() As Integer Dim Type As String Dim Choice As Integer Dim Value As Double Dim IndoorGarageAnswer As MsgBoxResult Dim Answer As String

Type = "Unknown"

Choice = CInt(InputBox("Enter the type of house you want to purchase" & vbCrLf & "1. Single Family" & vbCrLf & "2. Townhouse" & vbCrLf & "3. Condominium" & vbCrLf & vbCrLf & "You Choice? ")) Value = CDbl(InputBox("Up to how much can you afford?"))

Type = Choose(Choice, "Single Family", "Townhouse", "Condominium")

IndoorGarageAnswer = MsgBox("Does the house have an indoor garage (1=Yes/0=No)? ", MsgBoxStyle.Question Or MsgBoxStyle.YesNo, "Real Estate")

"Order Total:" & vbTab & FormatCurrency(OrderTotal) & vbCrLf & "==========================="

MsgBox(OrderInvoice, _ MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental")

RestartOrderProcessing: Answer = MsgBox("Do you want to process another order?", MsgBoxStyle.Information Or MsgBoxStyle.YesNo, "Bethesda Car Rental") Loop Until Answer = MsgBoxResult.No Return 0 End Function

End Module

Page 230: Microsoft Visual Basic 2010 Tutorial

Answer = IIf(IndoorGarageAnswer = MsgBoxResult.Yes, "Yes", "No")

If (Type = "Single Family") And (Value <= 550000) And (IndoorGarageAnswer = MsgBoxResult.Yes) Then MsgBox("Desired House Type: " & vbTab & Type & vbCrLf & "Maximum value afforded: " & vbTab & FormatCurrency(Value) & vbCrLf & "House has indoor garage: " & vbTab & Answer) MsgBox("Desired House Matched") Else MsgBox("The House Doesn't Match the Desired Criteria") End If

Return 0 End Function

End Module

We saw that when two conditions are combined, the compiler first checks the first condition,followed by the second. In the same way, if three conditions need to be considered, the compilerevaluates the truthfulness of the first condition:

Type of House

A

Town House

False

If the first condition (or any condition) is false, the whole condition is false, regardless of theoutcome of the other(s). If the first condition is true, then the second condition is evaluated for itstruthfulness:

Type of House Property Value

A B

Single Family $655,000

True False

If the second condition is false, the whole combination is considered false:

A B A && B

True False False

When evaluating three conditions, if either the first or the second is false, since the wholecondition would become false, there is no reason to evaluate the third. If both the first and thesecond conditions are false, there is also no reason to evaluate the third condition. Only if the firsttwo conditions are true will the third condition be evaluated whether it is true:

Type of House Property Value Indoor Garage

A B C

Single Family $425,650 None

True True False

The combination of these conditions in a logical conjunction can be written as A && B && C. If thethird condition is false, the whole combination is considered false:

A B A && B C A && B && C

True True True False False

From our discussion so far, the truth table of the combinations can be illustrated as follows:

A B C A && B && C

False Don't Care Don't Care False

True False Don't Care False

True True False False

The whole combination is true only if all three conditions are true. This can be illustrated asfollows:

A B C A && B && C

False False False False

False False True False

True False False False

True False True False

False True False False

Page 231: Microsoft Visual Basic 2010 Tutorial

False True True False

True True False False

True True True True

Logical Disjunction: OR

Introduction

Our real estate company has single family homes, townhouses, and condominiums. All of thecondos have only one level, also referred to as a story. Some of the single family homes have onestory, some have two and some others have three levels. All townhouses have three levels.

Another customer wants to buy a home. The customer says that he primarily wants a condo, but ifour real estate company doesn't have a condominium, that is, if the company has only houses,whatever it is, whether a house or a condo, it must have only one level (story) (due to an illness,the customer would not climb the stairs). When considering the properties of our company, wewould proceed with these statements:

1. The property is a condominium

2. The property has one story

If we find a condo, since all of our condos have only one level, the criterion set by the customer istrue. Even if we were considering another (type of) property, it wouldn't matter. This can beresumed in the following table:

Type of House House

Condominium True

The other properties would not be considered, especially if they have more than one story:

Number of Stories Value

3 False

We can show this operation as follows:

Condominium One Story Condominium or 1 Story

True False True

Creating a Logical Disjunction

To support "either or" conditions in the Visual Basic language, you use the Or operator. Here is anexample:

Module Exercise

Public Function Main() As Integer Dim Type As String Dim Choice As Integer Dim Stories As Short Type = "Unknown"

Choice = CInt(InputBox("Enter the type of house you want to purchase" & vbCrLf & "1. Single Family" & vbCrLf & "2. Townhouse" & vbCrLf & "3. Condominium" & vbCrLf & vbCrLf & "You Choice? ", "Real Estate", 1))

Type = Choose(Choice, "Single Family", "Townhouse", "Condominium") Stories = CShort(InputBox("How many stories?", "Real Estate", 1))

If Choice = 1 Or Stories = 1 Then MsgBox("Desired House Type:" & vbTab & Type & vbCrLf & "Number of Stories:" & vbTab & vbTab & Stories) MsgBox("Desired House Matched") Else MsgBox("The House Doesn't Match the Desired Criteria") End If

Return 0 End Function

End Module

As done for the And operator, to make a logical disjunction easy to read, you can include eachstatement in parentheses:

Page 232: Microsoft Visual Basic 2010 Tutorial

Module Exercise

Public Function Main() As Integer . . . No Change

If (Choice = 1) Or (Stories = 1) Then MsgBox("Desired House Type:" & vbTab & Type & vbCrLf & "Number of Stories:" & vbTab & vbTab & Stories) MsgBox("Desired House Matched") Else MsgBox("The House Doesn't Match the Desired Criteria") End If

Return 0 End Function

End Module

Here is an example of running the program:

Suppose that, among the properties our real estate company has available, there is nocondominium. In this case, we would then consider the other properties:

Type of House House

Single Family False

If we have a few single family homes, we would look for one that has only one story. Once we findone, our second criterion becomes true:

Type ofHouse One Story Condominium OR 1 Story

False True True

This can be illustrated in the following run of the above program:

Page 233: Microsoft Visual Basic 2010 Tutorial

If we find a condo and it is one story, both criteria are true. This can be illustrated in the followingtable:

Type ofHouse One Story Condominium OR 1 Story

False True True

True True True

The following run of the program demonstrates this:

A Boolean OR operation produces a false result only if BOTH conditions ARE FALSE:

If Condition1 is If Condition2 is Condition1 OR Condition2

False True True

True False True

True True True

False False False

Here is another example of running the program:

Page 234: Microsoft Visual Basic 2010 Tutorial

Practical Learning: Using Logical Disjunctions

1. Start Microsoft Visual Basic and create a Console Application named BCR7 (or open the BCR6application from the previous lesson and go to the next section)

2. In the Solution Explorer, right-click Module1.vb and click Rename

3. Type BethesdaCarRental.vb and press Enter

4. Change the document as follows:

Module BethesdaCarRental Private Function GetEmployeeName() As String Dim Name As String Dim EmployeeNumber As Long

EmployeeNumber = CLng(InputBox("Employee number (who processed this order):", "Bethesda Car Rental", "00000"))

If EmployeeNumber = 22804 Then Name = "Helene Mukoko" ElseIf EmployeeNumber = 92746 Then Name = "Raymond Kouma" ElseIf EmployeeNumber = 54080 Then Name = "Henry Larson" ElseIf EmployeeNumber = 86285 Then Name = "Gertrude Monay" Else Name = "Unknown" End If

Return Name End Function

Private Function GetCarCondition() As String Dim Status As Integer Dim Condition As String

Do Status = CInt(InputBox("After inpecting it, enter car condition:" & vbCrLf & "1. Excellent - No scratch, no damage, no concern" & vbCrLf & "2. Good - Some concerns (scratches or missing something)." & "Make sure the customer is aware." & vbCrLf & "3. Drivable - The car is good enough to drive." & "The customer must know the status of the car " & "and agree to rent it", "Bethesda Car Rental", 1))

Select Case Status Case 1 Condition = "Excellent" Case 2 Condition = "Good" Case 3 Condition = "Drivable" Case Else Condition = "Unknown" End Select

If (Status < 1) Or (Status > 3) Then

Page 235: Microsoft Visual Basic 2010 Tutorial

MsgBox("Please enter a valid number between 1 and 3", MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") End If Loop Until (Status > 0) And (Status < 4)

Return Condition End Function

Private Function GetTankLevel() As String Dim Level As Integer Dim Result As String

Do Level = CInt(InputBox("Enter Tank Level:" & vbCrLf & "1. Empty" & vbCrLf & "2. 1/4 Empty" & vbCrLf & "3. 1/2 Full" & vbCrLf & "4. 3/4 Full" & vbCrLf & "5. Full", "Bethesda Car Rental", 1)) Result = Microsoft.VisualBasic.Switch(Level = 1, "Empty", Level = 2, "1/4 Empty", Level = 3, "1/2 Full", Level = 4, "3/4 Full", True, "Full") If (Level < 1) Or (Level > 5) Then MsgBox("Invalid tank level. " & "Please try again.", MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") End If Loop While (Level < 1) Or (Level > 5)

Return Result End Function

Public Function Main() As Integer Dim EmployeeName As String Dim CustomerName As String Dim TagNumber As String, CarSelected As String Dim CarCondition As String Dim TankLevel As String Dim RentStartDate As Date, RentEndDate As Date Dim NumberOfDays As Integer Dim RateType As String, RateApplied As Double Dim OrderTotal As Double Dim OrderInvoice As String Dim Answer As MsgBoxResult

RateApplied = 0 RateType = "Weekly Rate" OrderTotal = RateApplied

Do EmployeeName = GetEmployeeName()

CustomerName = InputBox("Enter Customer Name:", _ "Bethesda Car Rental", "John Doe") TagNumber = InputBox("Enter the tag number of the car to rent:", "Bethesda Car Rental", "000000")

CarSelected = Microsoft.VisualBasic.Switch( TagNumber = "297419", "BMW 335i", TagNumber = "485M270", "Chevrolet Avalanche", TagNumber = "247597", "Honda Accord LX", TagNumber = "924095", "Mazda Miata", TagNumber = "772475", "Chevrolet Aveo", TagNumber = "M931429", "Ford E150XL", TagNumber = "240759", "Buick Lacrosse", True, "Unidentified Car")

CarCondition = GetCarCondition()

TankLevel = GetTankLevel()

RentStartDate = CDate(InputBox("Enter Rent Start Date:", "Bethesda Car Rental", #1/1/1900#)) RentEndDate = CDate(InputBox("Enter Rend End Date:", "Bethesda Car Rental", #1/1/1900#))

If RentEndDate < RentStartDate Then MsgBox("The values you entered for the start and end dates " & "are not consecute. The rent start date must occur " & "prior to the rent end date", MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") GoTo RestartOrderProcessing End If

NumberOfDays = DateDiff(DateInterval.Day, RentStartDate, RentEndDate)

RateApplied = CDbl(InputBox("Enter Rate Applied:", _ "Bethesda Car Rental", 0))

Dim TemporaryRate As Double

Select Case NumberOfDays Case 0, 1

Page 236: Microsoft Visual Basic 2010 Tutorial

5. Execute the application

6. Enter the employee number as 92746, the customer name as James Wiley, the tag numberas 297419, the car condition as 1, the tank level as 5, the start date as 11/07/2008, theend date as 11/10/2008, and the rate applied 49.95

7. When asked whether you want to process another order, click Yes

8. Enter the employee number as 54080, the customer name as Sunil Ajat, the tag number as240759, the car condition as 3, the tank level as 3, the start date as 11/05/2008, the enddate as 11/15/2008, and the rate applied 70.25

9. When asked whether you want to process another order, click Yes

10. Enter the employee number as 22804, the customer name as George Livingstone, the tagnumber as 924095, the car condition as 2, the tank level as 4, the start date as09/15/2008, the end date as 09/19/2008, and the rate applied 65.75

11. When asked whether you want to process another order, click Yes

12. Enter the employee number as 86285, the customer name as Antoinette D. Liel, the tagnumber as 485M270, the car condition as 2, the tank level as 2, the start date as11/15/2008, the end date as 11/17/2008, and the rate applied 55.50

13. When asked whether you want to process another order, click No

14. Close the message box and the DOS window to return to your programming environment

Combinations of Disjunctions

As opposed to evaluating only two conditions, you may face a situation that presents three of themand must consider a combination of more than two conditions. You would apply the same logicalapproach we reviewed for the logical conjunction, except that, in a group of logical disjunctions, ifone of them is true, the whole statement becomes true.

RateType = "Daily Rate" OrderTotal = RateApplied Case 2 RateType = "Weekend Rate" TemporaryRate = RateApplied * 50 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * 2 Case 2 To 7 RateType = "Weekly Rate" TemporaryRate = RateApplied * 25 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * NumberOfDays Case Is > 8 RateType = "Monthly Rate" TemporaryRate = RateApplied * 15 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * NumberOfDays End Select

OrderInvoice = "===========================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Order Processing =-=-==" & vbCrLf & "------------------------------------------------" & vbCrLf & "Processed by:" & vbTab & EmployeeName & vbCrLf & "Processed for:" & vbTab & CustomerName & vbCrLf & "------------------------------------------------" & vbCrLf & "Car Selected:" & vbCrLf & vbTab & "Tag #:" & vbTab & TagNumber & vbCrLf & vbTab & "Car:" & vbTab & CarSelected & vbCrLf & vbTab & "Tank:" & vbTab & TankLevel & vbCrLf & "Car Condition:" & vbTab & CarCondition & vbCrLf & "------------------------------------------------" & vbCrLf & "Start Date:" & vbTab & RentStartDate & vbCrLf & "End Date:" & vbTab & RentEndDate & vbCrLf & "Nbr of Days:" & vbTab & NumberOfDays & vbCrLf & "------------------------------------------------" & vbCrLf & "Rate Type:" & vbTab & RateType & vbCrLf & "Rate Applied:" & vbTab & FormatCurrency(RateApplied) & vbCrLf & "Order Total:" & vbTab & FormatCurrency(OrderTotal) & vbCrLf & "==========================="

MsgBox(OrderInvoice, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental")

RestartOrderProcessing: Answer = MsgBox("Do you want to process another order?", MsgBoxStyle.Information Or MsgBoxStyle.YesNo, "Bethesda Car Rental") Loop Until Answer = MsgBoxResult.No Return 0 End Function

End Module

Page 237: Microsoft Visual Basic 2010 Tutorial

Previous Copyright © 2008-2010 FunctionX, Inc. Home

Page 238: Microsoft Visual Basic 2010 Tutorial

Introduction to Classes

Programmer-Defined Types

Introduction

In the Visual Basic language, you can combine a group of variables into an entity. These variablesbecome considered as one. You can then declare one or more elaborate variables from thisenhanced type. Such a new type is called a class.

Practical Learning: Introducing Classes

1. Start Microsoft Visual Basic and create a Console Application named DepartmentStore1

2. In the Solution Explorer, right-click Module1.vb and click Rename

3. Set the name to DepartmentStore.vb, press Enter, and accept to rename the file

4. Change the document as follows:

Public Module DepartmentStore

Public Function Main() As Integer

Return 0 End Function

End Module

5. Save the file

Creating a Class

Imagine you want to represent a rectangle as a geometric object:

You can declare each of its various parts as a variable. Here is an example:

Public Module Exercise

Public Function Main() As Integer Dim RectLength As Double Dim RectHeight As Double

RectLength = 24.55 : RectHeight = 20.75

MsgBox("=-= Rectangle Characteristics =-=" & vbCrLf & _ "Length: " & vbTab & RectLength & vbCrLf & _ "Height: " & vbTab & RectHeight)

Return 0 End Function

End Module

This would produce:

Page 239: Microsoft Visual Basic 2010 Tutorial

If you want to treat the whole rectangle as one object, you can create a class for it. To create a class, you can use theClass keyword followed by a name. The name of a class follows the rules we have applied so far for variable and functionnames. To declare a class called Rectangle, you would start with the following:

Class Rectangle

As a name that represents a group of items, a class has a body that would be used to define the items that compose it.The body of a class starts after its name.

To indicate the end of the class, type End Class. Therefore, a class can be created as follows:

Class Rectangle

End Class

Since a class is a combination of other variables, you declare each variable inside of the body of the class. Each item thatcomposes the class is represented as a complete variable declared with a name and a data type. By adding a Length anda Height variables, our class would become:

Class Rectangle Dim Length As Double Dim Height As DoubleEnd Class

The items that compose a class are called members of the class. When creating the members of a class, you can omit theDim keyword:

Class Rectangle Length As Double Height As DoubleEnd Class

To create a class in Microsoft Visual Studio:

a. On the main menu, you can click Project -> Add Class... Alternatively, in the Solution Explorer, you can right-clickthe name of the project, position the mouse on Add, and click Class

b. In the Templates section of the Add New Item dialog box, make sure the Class item is selected. Accept thesuggested name or replace it in the Name text box

c. Click Add

Practical Learning: Introducing Class Members

Imagine you want to write a (console-based) program for a department store and the customerhas given you a preliminary catalog as follows:

Page 240: Microsoft Visual Basic 2010 Tutorial

Stock #: 437876Crinkled Georgette Dress

Unit: $42.95

Stock #: 790475New Wool Comfort Pants

$38.75

Stock #: 740797Pencil Skirt

$25.75

Stock: 608432Silver 1/10-ct. T.W. Diamond

Heart-Link Bracelet$95.85

Stock #: 759470Multistriped Organic Cotton

Dress Shirt$35.50

Stock #: 487046Modest Dress Heels

$35.50

Each item in this catalog is represented by its Stock number, its name or description, and itsprice. Based on this, you can create a class that represents each item.

1. To create a new class, on the main menu, click Project -> Add Class...

2. In the Templates section of the Add New Item dialog box, make sure the Class item is selected.Set the Name to StoreItem

3. Click Add

4. Change the document as follows:

Public Class StoreItem Dim ItemNumber As Long Dim ItemName As String Dim UnitPrice As DoubleEnd Class

5. Save the file

Class Members and Access Modifiers

Introduction

In Lesson 4, we saw how to control access to members of a module. When you create a class, you also exercise thiscontrol. You define what member variables can be accessed from outside the class and members that must not beaccessed outside. This means that when creating a class, you specify what members are friendly, public, or private.

Page 241: Microsoft Visual Basic 2010 Tutorial

The Friendly Members of a Class

A member variable of a class is referred to as a friend if it can be accessed by any class or module of the sameapplication. Classes and modules outside of its application cannot access such a member. To create such a membervariable, precede it with the Friend keyword. Here is an example:

Class Rectangle Friend Height As DoubleEnd Class

Practical Learning: Controlling the Access Level

1. To specify the member variables as public, change the file as follows:

Public Class StoreItem Friend ItemNumber As Long Friend ItemName As String Friend UnitPrice As DoubleEnd Class

2. Save the file

The Public Members of a Class

Some of the member variables of a class must be accessed outside of a class and sometimes you will want a member tobe accessible outside of its application. Such a member is referred to a public. To create a public member of a class,precede it with the Public keyword. Here is an example:

Class Rectangle Public Length As Double Friend Height As DoubleEnd Class

Classes and Access Modifiers

Introduction

In Lesson 4, we saw how to control access to a module. You can exercise the same level of control for a class. You canmake a class friendly, private, or public.

A Private Class

If you create a class in a code file but the class must be accessed only locally, you can define it as private. A class isreferred to as private if it can be accessed only within the module where it is created, that is, only by members of thesame file. Classes and modules outside of its file or outside of the application cannot access such a class.

To create a private class, precede it with the Private keyword. Here is an example:

Module Exercise REM This class can be accessed only inside this module Private Class Rectangle Public Length As Double Friend Height As Double End Class

Public Function Main() As Integer Return 0 End Function

End Module

A Friendly Class

Instead of hiding a class from the rest of the application, you may want other modules or classes of the same applicationto have access to it. Such a class is referred to as friendly. A friendly class can be accessed by code within its application.Classes and modules outside of its application do not have access to such a class.

To create a friendly class, precede it with the Friend keyword. Here is an example:

Friend Class Square Public Side As DoubleEnd Class

A Public Class

Page 242: Microsoft Visual Basic 2010 Tutorial

Although you may think of working only in Visual Basic, in some cases, you may create a class and want to share it withcode written in another language such as C++/CLI or C#, to make this possible, you can give "public" access to yourclass.

If you want your class to be accessible to code written in other languages, precede the Class keyword with Public whencreating it. Here is an example:

Public Class Circle Friend Radius As DoubleEnd Class

Using a Class as a Variable

Introduction

After creating a class, to use it in a program, you can declare it as a variable. Here is an example:

Module Exercise Private Class Rectangle Public Length As Double Friend Height As Double End Class

Public Function Main() As Integer Dim Recto As Rectangle

Return 0 End Function

End Module

After declaring the variable, you must ask the compiler to reserve enough memory for all the member variables of theclass. The compiler would do this. Later on, to access any member variable of the class, you must get a reference to thearea of memory where the members of the class are located. To do this, when declaring the variable for the class, toreserve the necessary area of memory, use the New operator followed by the name of the class and assign thisexpression to the variable. Here is an example:

Module Exercise Private Class Rectangle Public Length As Double Friend Height As Double End Class

Public Function Main() As Integer Dim Recto As Rectangle

Recto = New Rectangle

Return 0 End Function

End Module

Instead of first declaring the variable before allocating memory for it, you can take care of this directly when declaringthe variable by inserting the New operator between the As keyword and the name of the class. This can be done asfollows:

Module Exercise Private Class Rectangle Public Length As Double Friend Height As Double End Class

Public Function Main() As Integer Dim Recto As New Rectangle

Return 0 End Function

End Module

In C++ and Visual Basic, you can omit or add parentheses to the name of the class when allocating memory forit, like this:

Module Exercise Private Class Rectangle Public Length As Double Friend Height As Double End Class

Public Function Main() As Integer Dim Recto As Rectangle

Page 243: Microsoft Visual Basic 2010 Tutorial

Recto = New Rectangle()

Return 0 End Function

End Module

or like this:

Module Exercise Private Class Rectangle Public Length As Double Friend Height As Double End Class

Public Function Main() As Integer Dim Recto As New Rectangle()

Return 0 End Function

End Module

In C#, you must always use parentheses.

Any of these techniques produces the same result. It is just a matter of taste. A variable declared of a class is also calledan object.

Practical Learning: Creating an Object

1. Access the Program.vb file and declare a variable as follows:

Public Module DepartmentStore

Public Function Main() As Integer Dim dptStore As StoreItem

dptStore = New StoreItem

Return 0 End Function

End Module

2. Save the file

Period: .

After declaring the variable and allocating memory for it, the compiler reserves enough memory to accommodate all themembers of the class and those members become available to you.

To access the member of a class, type the name of the variable, followed by a period, followed by the name of themember you want. The member you are trying to use must be part of the class. Here is an example:

Module Exercise Private Class Rectangle Public Length As Double Friend Height As Double End Class

Public Function Main() As Integer Dim Recto As Rectangle

Recto.Length

Return 0 End Function

End Module

If you are using either Microsoft Visual Basic or another editor equipped with Intellisense, after you type the period, thelist of members would appear:

Page 244: Microsoft Visual Basic 2010 Tutorial

If you know the name of the member, you can start typing it:

Once the desired member is highlighted, press the Space bar or Tab

If you see the name of the member in the list, you can double-click click it

If the list doesn't appear, press Ctrl + Space bar

If you don't want to use the list displayed by the Code Editor, press Esc. Once you have specified what member you wantto use, you can assign it the desired value. Here is an example:

Module Exercise Private Class Rectangle Public Length As Double Friend Height As Double End Class

Public Function Main() As Integer Dim Recto As Rectangle

Recto.Length = 24.55 Return 0 End Function

End Module

In the same way, you can access all the desired members of a class and initialize them to complete the variable. Bydefault, each member variable must be initialized on its own line. Here are examples:

Module Exercise Private Class Rectangle Public Length As Double Friend Heigh

Page 245: Microsoft Visual Basic 2010 Tutorial

The Methods of a Class

Methods Fundamentals

Introduction

The variables of a program cannot perform assignments. In the same way, the member variablesof a class cannot perform actions. So far, we were using procedures to do that. In the same way,to create a class as complete as possible, you can equip it with its own procedures. Such aprocedure is created as a member of the class.

A procedure that is made a member of a class is called a method.

Imagine you want to write a (console-based) program for a department store and the customerhas given you a preliminary catalog as follows:

Stock #: 437876Crinkled Georgette Dress

Unit: $42.95

Stock #: 790475New Wool Comfort Pants

$38.75

Stock #: 740797Pencil Skirt

$25.75

Stock: 608432Silver 1/10-ct. T.W. Diamond

Heart-Link Bracelet$95.85

Stock #: 759470Multistriped Organic Cotton

Dress Shirt$35.50

Stock #: 487046Modest Dress Heels

$35.50

Each item in this catalog is represented by its Stock number, its name or description, and itsprice. Based on this, you can create a class that represents each item.

Practical Learning: Introducing Methods

1. Start Microsoft Visual Basic and create a Console Application named DepartmentStore1

Page 246: Microsoft Visual Basic 2010 Tutorial

2. In the Solution Explorer, right-click Module1.vb and click Rename

3. Set the name to DepartmentStore.vb, press Enter, and accept to rename the file

4. Change the document as follows:

Public Module DepartmentStore

Public Function Main() As Integer

Return 0 End Function

End Module

5. Save the file

6. To create a new class, on the main menu, click Project -> Add Class...

7. In the Templates section of the Add New Item dialog box, make sure the Class item isselected.Set the Name to StoreItem

8. Click Add

9. Change the document as follows:

Public Class StoreItem Friend ItemNumber As Long Friend ItemName As String Friend UnitPrice As DoubleEnd Class

10. Save the file

11. To use a DepartmentStore object, change the Program.vb file as follows:

Public Module DepartmentStore

Public Function Main() As Integer Dim dptStore As StoreItem

dptStore = New StoreItem

With dptStore .ItemNumber = 437876 .ItemName = "Crinkled Georgette Dress" .UnitPrice = 42.95

MsgBox("=-= Department Store =-=" & vbCrLf & _ "Item #:" & vbTab & vbTab & .ItemNumber & vbCrLf & _ "Item Name:" & vbTab & .ItemName & vbCrLf & _ "Unit Price: " & vbTab & FormatCurrency(.UnitPrice), _ MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _ "Department Store") End With

Return 0 End Function

End Module

12. Execute the application to test it

13. Click OK and return to your programming environment

Creating a Method

To create a method, in the body of a class, use the same formula we learned in Lesson 5. Forexample, to create a sub procedure, you use the following formula:

Class Class Name

Sub ProcedureName()

End Sub

End Class

Here is an example:

Private Class Rectangle

Sub Show() End Sub

Page 247: Microsoft Visual Basic 2010 Tutorial

End Class

In the body of the method, do whatever you want. For example, you can call the MsgBox()function to display a message. Here is an example:

Private Class Rectangle

Sub Show() MsgBox("Whatever") End Sub

End Class

Practical Learning: Creating a Method

1. Access the StoreItem.vb file

2. Create two methods as follows:

Public Class StoreItem Friend ItemNumber As Long Friend ItemName As String Friend UnitPrice As Double

Sub Create() ItemNumber = 790475 ItemName = "New Wool Comfort Pants" UnitPrice = 38.75 End Sub

Sub Display() MsgBox("=-= Department Store =-=" & vbCrLf & _ "Item #:" & vbTab & vbTab & ItemNumber & vbCrLf & _ "Item Name:" & vbTab & ItemName & vbCrLf & _ "Unit Price: " & vbTab & FormatCurrency(UnitPrice), _ MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _ "Department Store") End SubEnd Class

3. Save the file

Accessing a Method

To access a method outside of its class, you can use the period operator as we saw for themember variables. Here is an example

Public Module Exercise Private Class Rectangle Sub Show() MsgBox("Whatever") End Sub End Class

Public Function Main() As Integer Dim Recto As Rectangle

Recto = New Rectangle

Recto.Show()

Return 0 End Function

End Module

In the same way, you can use a With statement to access a method of a class.

Practical Learning: Calling the Methods of a Class

1. Access the DepartmentStore.vb file

2. To use the methods of the class, change the code as follows:

Public Module DepartmentStore

Public Function Main() As Integer Dim dptStore As StoreItem

dptStore = New StoreItem

With dptStore .Create() .Display() End With

Return 0 End Function

Page 248: Microsoft Visual Basic 2010 Tutorial

End Module

3. Execute the application to test it

4. Click OK and return to your programming environment

Using the Member Variables of a Class

In the previous sections, we saw how to create member variables inside of a class. Here is anexample:

Class Rectangle Length As Double Height As Double

Sub Show()

End SubEnd Class

When you have created a member variable in a class, it is available to all methods of the sameclass. This means that, to use it from a method of the same class, you do not have to declare avariable for the class. Here is an example:

Public Module Exercise Private Class Rectangle Public Length As Double Friend Height As Double

Sub Show() MsgBox("=-= Rectangle Characteristics =-=" & vbCrLf & _ "Length: " & vbTab & Length & vbCrLf & _ "Height: " & vbTab & Height) End Sub End Class

Public Function Main() As Integer Dim Recto As Rectangle

Recto = New Rectangle Recto.Length = 24.55 : Recto.Height = 20.75 Recto.Show()

Return 0 End Function

End Module

Notice that the Length and the Height member variables are accessed inside of the Show() methodwithout an instance of the Rectangle class.

Details on Implementing Methods

The Case of Function Methods

So far, we have seen how to create sub procedure in a class, which is a method that does notreturn a value. Like a normal procedure, a method can be made to return a value, in which case itwould be a function. To create a method as a function, use the same techniques we have used sofar to create a function. Here is an example:

Friend Class Rectangle Public Length As Double Public Height As Double

Function Assign() As Double

End FunctionEnd Class

After declaring a procedure, in its body, you can implement the expected behavior. As seen for asub procedure, when a method has been created, it has access to all of the other members of thesame class. This means that you don't have to re-declare a member of a class to access it in amethod. Based on this, you can manipulate any member variable of the same class as you wish.This means that, naturally, you do not have to create a function method to change the value of amember variable. A normal sub procedure can take care of this. Instead, you would create amethod if you need to perform a calculation and get a value from it instead of storing that value inone of the member variables. Here is an example:

Friend Class Rectangle Public Length As Double Public Height As Double

Page 249: Microsoft Visual Basic 2010 Tutorial

Function Assign() As Double

End Function

Function Perimeter() As Double

End FunctionEnd Class

Therefore, in the body of the function, you can access a member variable, you can call anothermethod of the same class, or you can use an external value as you see fit. When the functionexits, make sure it returns the appropriate value based on its type. Like the member variables,the methods can be accessed outside of the class using the period operator. Here is an example:

Public Module Exercise Friend Class Rectangle Public Length As Double Public Height As Double

Function Perimeter() As Double Return (Length + Height) * 2 End Function

Function Area#() Return Length * Height End Function End Class

Public Function Main() As Integer Dim Recto As Rectangle

Recto = New Rectangle

Recto.Length = 42.58 : Recto.Height = 28.08

MsgBox("=-= Rectangle Characteristics =-=" & vbCrLf & _ "Length: " & vbTab & vbTab & Recto.Length & vbCrLf & _ "Height: " & vbTab & vbTab & Recto.Height & vbCrLf & _ "Perimeter: " & vbTab & Recto.Perimeter() & vbCrLf & _ "Area: " & vbTab & vbTab & Recto.Area())

Return 0 End FunctionEnd Module

This would produce:

Like a sub procedure that is created as a method, a member function of a class can be madeprivate, public, or friendly. It follows the exact same rules we reviewed early.

Practical Learning: Implementing the Methods of a Class

1. Start Microsoft Visual Basic and create a Console Application named DepartmentStore2

2. In the Solution Explorer, right-click Module1.vb and click Rename

3. Set the name to DepartmentStore.vb, press Enter, and accept to rename the file

4. To add two methods of the class, change the file as follows:

Module DepartmentStore

Public Class StoreItem Public ItemNumber As Long Public ItemName As String Public UnitPrice As Double

Public Sub RegisterStoreItem() ItemNumber = CLng(InputBox("=#= Department Store =#=" & vbCrLf & _ " --- Item Registration ---" & vbCrLf & _ vbCrLf & vbCrLf & vbCrLf & _ "Enter Item #", "Department Store")) ItemName = InputBox("=#= Department Store =#=" & vbCrLf & _ " --- Item Registration ---" & vbCrLf & _ "Enter Item Name", "Department Store")

Page 250: Microsoft Visual Basic 2010 Tutorial

UnitPrice = CDbl(InputBox("=#= Department Store =#=" & vbCrLf & _ " --- Item Registration ---" & vbCrLf & _ vbCrLf & vbCrLf & vbCrLf & _ "Enter Unit Price", "Department Store")) End Sub

Public Sub ShowItem() MsgBox("=-= Department Store =-=" & vbCrLf & _ "--- Store Inventory ---" & vbCrLf & _ "Item #:" & vbTab & vbTab & ItemNumber & vbCrLf & _ "Item Name:" & vbTab & ItemName & vbCrLf & _ "Unit Price:" & vbTab & FormatCurrency(UnitPrice), _ MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _ "Department Store") End Sub End Class

Public Function Main() As Integer Dim dptStore As StoreItem = New StoreItem

dptStore.RegisterStoreItem() dptStore.ShowItem()

Return 0 End Function

End Module

5. Execute the program to test it

6. Enter the item # as 740797

7. Enter the item name as Pencil Skirt

8. Enter the price as 25.75

9. Close the form and return to your programming environment

Page 251: Microsoft Visual Basic 2010 Tutorial

1.

Methods and Arguments

Like regular procedures we have used so far, methods can have arguments. The rules are thesame as we have applied them so far. When you create a method, it has direct access to allregular members of its class. This means that you don't have to create an argument for a membervariable of the same class. You would need an argument only if an external value would be passedto the method.

Methods Overloading

Just as done for regular procedures, a method of a class can be overloaded. To overload a method,create more than one method with the same name. The methods with same names must havedifferent rules in their arguments:

They can have different types of arguments. Here is an example:

Private Class EmployeeInformation REM Contractor Registration Private Sub Register(ByVal SalaryCategory As Integer)

End Sub

REM Full Time Employee Registration Private Sub Register(ByVal HourlySalary As Double)

End SubEnd Class

They can have a different number of arguments. Here is an example:

Private Class Geometry REM The area of a square Friend Function CalculateArea#(ByVal Side#) Area# = Side * Side End Function

REM The area of a rectangle Friend Function CalculateArea#(ByVal Length#, ByVal Height#) Area# = Length# * Height# End FunctionEnd Class

Any or both of these two rules must be respected.

Me

We have mentioned two techniques of accessing the members of a class, one consisted ofdeclaring a variable of the class, the other had to do with Shared members. We know already thatthe members of a class are made available to all other members of the same class without beingdeclared or qualified. Consider the following class:

Public Class Triangle Public Base As Double Public Height As Double Public Area As Double

Public Sub Display() Dim Area As Double Area = Base * Height / 2 End SubEnd Class

When the Area variable is used in the Display() method, there are two variables available andnamed Area. It makes it confusing to know what particular variable is being accessed. You can usea special member of a class that allows you to specify the member of a class when accessing it.This member is called Me.

When using Me, you can access any member of a class within any method of the same class. Hereis an example:

Public Module Exercise Public Class Triangle Public Base As Double Public Height As Double Public Area As Double

Public Sub Display() Dim Area As Double

Page 252: Microsoft Visual Basic 2010 Tutorial

' Using "this" to access the members of this class Me.Base = 24.55 Me.Height = 20.75

' You cannot use this to access Area because Area ' is not a member of this class Area = Me.Base * Me.Height / 2

MsgBox("Triangle Characteristics" & vbCrLf & _ "Base:" & vbTab & Me.Base & vbCrLf & _ "Height:" & vbTab & Me.Height & vbCrLf & _ "Area: " & vbTab & Area) ' Area is not a member of the Exercise class End Sub End Class

Public Function Main() As Integer Dim tri As Triangle = New Triangle tri.Display() Return 0 End Function

End Module

This would produce:

There are rules you must follow when using Me:

Me can never be declared: it is automatically implied when you create a class

Me cannot be used in a class A to access a member of class B

Me cannot be used in a Shared method. The following program will not compile because Me isused in the Display() method declared as a Shared method:

Public Class Triangle Public Base As Double Public Height As Double Public Area As Double

Public Shared Sub Display() Dim Area As Double

' Using "this" to access the members of this class Me.Base = 24.55 Me.Height = 20.75

' You cannot use this to access Area because Area ' is not a member of this class Area = Me.Base * Me.Height / 2

MsgBox("Triangle Characteristics" & vbCrLf & _ "Base:" & vbTab & Me.Base & vbCrLf & _ "Height:" & vbTab & Me.Height & vbCrLf & _ "Area: " & vbTab & Area) End SubEnd Class

Home Copyright © 2008-2010 FunctionX, Inc.

Page 253: Microsoft Visual Basic 2010 Tutorial

Class Construction and Destruction

Techniques of Initializing a Member Variable

Introduction

When you declare a variable, the compiler initializes its allocated memory with a default value.Consider the following program:

Public Module Exercise Private Class Square

Private Side As Double

Function CalculatePerimeter() As Double Return Side * 4 End Function

Function CalculateArea() As Double Return Side * Side End Function

Public Sub ShowMessage() MsgBox("Square Characteristics" & vbCrLf & _ "Side:" & vbTab & vbTab & FormatNumber(Side) & vbCrLf & _ "Perimeter:" & vbTab & _ FormatNumber(CalculatePerimeter()) & vbCrLf & _ "Area:" & vbTab & vbTab & FormatNumber(CalculateArea())) End Sub End Class

Public Function Main() As Integer Dim sqr As Square = New Square

sqr.ShowMessage()

Return 0 End FunctionEnd Module

This would produce:

Notice that this program indicates that the Side member variable of the Square class wasinitialized with 0. This means that, like the regular variables, the member variables of a class areinitialized by the compiler with default values that depend on the type of the variable. Forexample, a numeric member variable is initialized with 0 while a string-based variable is initializedwith an empty string.

After adding a member variable to a class, instead of relying on the default value assigned by thecompiler, you can initialized it with a value of your choice, depending on the type of the variable.You have various alternatives.

Imagine you want to write a (console-based) program for a department store and the customerhas given you a preliminary catalog as follows:

Page 254: Microsoft Visual Basic 2010 Tutorial

Stock #: 437876Crinkled Georgette Dress

Unit: $42.95

Stock #: 790475New Wool Comfort Pants

$38.75

Stock #: 740797Pencil Skirt

$25.75

Stock: 608432Silver 1/10-ct. T.W. Diamond

Heart-Link Bracelet$95.85

Stock #: 759470Multistriped Organic Cotton

Dress Shirt$35.50

Stock #: 487046Modest Dress Heels

$35.50

Each item in this catalog is represented by its Stock number, its name or description, and itsprice. Based on this, you can create a class that represents each item.

Practical Learning: Creating a Class

1. Create a Console Application named DepartmentStore3

2. In the Solution Explorer, right-click Module1.vb and click Rename

3. Set the name to DepartmentStore.vb, press Enter, and accept to rename the file

4. To create a new class, in the Solution Explorer, right-click DepartmentStore3 -> Add ->Class...

5. Set the Name to StoreItem and press Enter

6. Change the file as follows:

Public Enum ItemCategory Women Men Girls Boys Babies Jewelry Beauty Bedroom MiscellaneousEnd Enum

Public Class StoreItem Friend ItemNumber As Long Friend Category As ItemCategory Friend ItemName As String Friend UnitPrice As Double

Public Sub ShowItem() Dim StrCategory As String

Page 255: Microsoft Visual Basic 2010 Tutorial

Select Case Category Case ItemCategory.Women StrCategory = "Women" Case ItemCategory.Men StrCategory = "Men" Case ItemCategory.Girls StrCategory = "Girls" Case ItemCategory.Boys StrCategory = "Boys" Case ItemCategory.Babies StrCategory = "Babies" Case ItemCategory.Jewelry StrCategory = "Jewelry" Case ItemCategory.Beauty StrCategory = "Beauty" Case ItemCategory.Bedroom StrCategory = "Bedroom" Case Else StrCategory = "Miscellaneous" End Select

MsgBox("=-= Department Store =-=" & vbCrLf & _ "--- Store Inventory ---" & vbCrLf & _ "Item #:" & vbTab & vbTab & ItemNumber & vbCrLf & _ "Category:" & vbTab & StrCategory & vbCrLf & _ "Item Name:" & vbTab & ItemName & vbCrLf & _ "Unit Price:" & vbTab & FormatCurrency(UnitPrice), _ MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _ "Department Store") End SubEnd Class

7. Save All

Initialization of a Member Variable

One way you can initialize a member variable is to assign it the desired value when declaring it.Here is an example:

Public Module Exercise Private Class Square Private Side As Double = 48.25

Function CalculatePerimeter() As Double Return Side * 4 End Function

Function CalculateArea() As Double Return Side * Side End Function

Public Sub Message() MsgBox("Square Characteristics" & vbCrLf & _ "Side:" & vbTab & vbTab & FormatNumber(Side) & vbCrLf & _ "Perimeter:" & vbTab & _ FormatNumber(CalculatePerimeter()) & vbCrLf & _ "Area:" & vbTab & vbTab & FormatNumber(CalculateArea())) End Sub End Class

Public Function Main() As Integer Dim sqr As Square = New Square

sqr.Message()

Return 0 End FunctionEnd Module

This would produce:

Notice that, this time, the default value assigned to the member variable applies. Instead ofinitializing a member variable when declaring it, you can create a method that would be used to dothis. Here is an example:

Public Class Square Private side As Double

Public Sub SetSide() side = 48.25 End SubEnd Class

Page 256: Microsoft Visual Basic 2010 Tutorial

Such a method can also be used to initialize more than one value. When you create a method usedto initialize one or more member variables of a class, if you want the initialization to apply, youmust make sure that you call that method first before calling other methods of the class.

Just as you can create a method to initialize the member(s) of a class, you can overload thatmethod with different versions to perform different initializations. Here are examples:

Public Module Exercise Private Class Square Private side As Double

Public Sub SetSide() side = 48.25 End Sub

Public Sub SetSide(ByVal sd As Double) side = sd End Sub

Function CalculatePerimeter() As Double Return Side * 4 End Function

Function CalculateArea() As Double Return Side * Side End Function

Public Sub Message() MsgBox("Square Characteristics" & vbCrLf & _ "Side:" & vbTab & vbTab & FormatNumber(Side) & vbCrLf & _ "Perimeter:" & vbTab & _ FormatNumber(CalculatePerimeter()) & vbCrLf & _ "Area:" & vbTab & vbTab & FormatNumber(CalculateArea())) End Sub End Class

Public Function Main() As Integer Dim sqr As Square = New Square

sqr.SetSide() sqr.Message()

Dim sd As Double

sd = CDbl(InputBox("Enter Square Side: ")) sqr.SetSide(sd)

sqr.Message()

Return 0 End FunctionEnd Module

Here an example of running the program:

Notice that, although the Square.Side member variable is private, you cab call the SetSide() publicmethod to initialize it before displaying the characteristics of a square.

Practical Learning: Initializing the Member Variables of a Class

Page 257: Microsoft Visual Basic 2010 Tutorial

1. Change the StoreItem class as follows:

Public Enum ItemCategory Women Men Girls Boys Babies Jewelry Beauty Bedroom MiscellaneousEnd Enum

Public Class StoreItem Friend ItemNumber As Long Friend Category As ItemCategory Friend ItemName As String Friend UnitPrice As Double

Public Sub Initialize(ByVal Number As Long, _ ByVal Type As ItemCategory, _ ByVal Name As String, _ ByVal Price As Double) ItemNumber = Number Category = Type ItemName = Name UnitPrice = Price End Sub

Public Sub ShowItem() Dim StrCategory As String

Select Case Category Case ItemCategory.Women StrCategory = "Women" Case ItemCategory.Men StrCategory = "Men" Case ItemCategory.Girls StrCategory = "Girls" Case ItemCategory.Boys StrCategory = "Boys" Case ItemCategory.Babies StrCategory = "Babies" Case ItemCategory.Jewelry StrCategory = "Jewelry" Case ItemCategory.Beauty StrCategory = "Beauty" Case ItemCategory.Bedroom StrCategory = "Bedroom" Case Else StrCategory = "Miscellaneous" End Select

MsgBox("=-= Department Store =-=" & vbCrLf & _ "--- Store Inventory ---" & vbCrLf & _ "Item #:" & vbTab & vbTab & ItemNumber & vbCrLf & _ "Category:" & vbTab & StrCategory & vbCrLf & _ "Item Name:" & vbTab & ItemName & vbCrLf & _ "Unit Price:" & vbTab & FormatCurrency(UnitPrice), _ MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _ "Department Store") End SubEnd Class

2. Access the DepartmentStore.vb file

3. To use a StoreItem object, change the file as follows:

Public Module DepartmentStore

Public Function Main() As Integer Dim Nbr As Long Dim Classification As ItemCategory Dim Description As String Dim Value As Double Dim Item As StoreItem

Nbr = 608432 Classification = ItemCategory.Jewelry Description = "Silver 1/10-ct. T.W. Diamond Heart-Link Bracelet" Value = 95.85

Item = New StoreItem Item.Initialize(Nbr, Classification, Description, Value) Item.ShowItem()

Return 0 End Function

End Module

4. Execute the application to see the result

Page 258: Microsoft Visual Basic 2010 Tutorial

5. Close the form and return to your programming environment

Class Construction

The Default Constructor

When you declare a variable of a class, a special method must be called to initialize the membersof that class. This method is automatically provided for every class and it is called a constructor.Whenever you create a new class, a constructor is automatically provided to it. This particularconstructor is called the default constructor. You have the option of creating it or not. Although aconstructor is created for your class, you can customize its behavior or change it as you see fit.

The constructor of a class is called New and it is created as a sub procedure. Here is an example:

Public Class Square Public Sub New() End SubEnd Class

Like every method, a constructor is equipped with a body. In this body, you can access any of themember variables (or method(s)) of the same class. Consider the following program:

Public Module Exercise Private Class Square Public Sub New() MsgBox("Square Builder") End Sub End Class

Public Function Main() As Integer Dim sq As Square = New Square

Return 0 End FunctionEnd Module

When executed, it would produce:

This shows that, when a class has been instantiated, its constructor is the first method to becalled. For this reason, you can use a constructor to initialize a class, that is, to assign defaultvalues to its member variables. Based on this, instead of initializing the member variable(s) of aclass when initializing it or them, or instead of creating a special method used to initialize themember variable(s) of a class, you can use a constructor to do this. The advantage of aconstructor is that it doesn't need to be called: it is automatically available whenever the class isinstantiated.

Practical Learning: Constructing a Class

1. Create a Console Application named DepartmentStore4

2. In the Solution Explorer, right-click Module1.vb and click Rename

3. Set the name to DepartmentStore.vb, press Enter, and accept to rename the file

4. To create a new class, in the Solution Explorer, right-click DepartmentStore4 -> Add ->Class...

5. Set the Name to StoreItem and click Add

6. Change the file as follows:

Page 259: Microsoft Visual Basic 2010 Tutorial

Public Enum ItemCategory Women Men Girls Boys Babies Jewelry Beauty Bedroom MiscellaneousEnd Enum

Public Class StoreItem Friend ItemNumber As Long Friend Category As ItemCategory Friend ItemName As String Friend UnitPrice As Double

Public Sub New() Me.ItemNumber = 0 Me.Category = ItemCategory.Miscellaneous Me.ItemName = "Unknown" Me.UnitPrice = 0D End Sub

Public Sub ShowItem() Dim StrCategory As String

Select Case Category Case ItemCategory.Women StrCategory = "Women" Case ItemCategory.Men StrCategory = "Men" Case ItemCategory.Girls StrCategory = "Girls" Case ItemCategory.Boys StrCategory = "Boys" Case ItemCategory.Babies StrCategory = "Babies" Case ItemCategory.Jewelry StrCategory = "Jewelry" Case ItemCategory.Beauty StrCategory = "Beauty" Case ItemCategory.Bedroom StrCategory = "Bedroom" Case Else StrCategory = "Miscellaneous" End Select

MsgBox("=-= Department Store =-=" & vbCrLf & _ "--- Store Inventory ---" & vbCrLf & _ "Item #:" & vbTab & vbTab & ItemNumber & vbCrLf & _ "Category:" & vbTab & StrCategory & vbCrLf & _ "Item Name:" & vbTab & ItemName & vbCrLf & _ "Unit Price:" & vbTab & FormatCurrency(UnitPrice), _ MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _ "Department Store") End SubEnd Class

7. Access the DepartmentStore.vb file

8. To use a StoreItem object, change the file as follows:

Public Module DepartmentStore

Public Function Main() As Integer Dim Item As StoreItem

Item = New StoreItem Item.ShowItem()

Return 0 End Function

End Module

9. Execute the application to see the result

Page 260: Microsoft Visual Basic 2010 Tutorial

10. Close the form and return to your programming environment

A Constructor With Argument(s)

In the previous section, we saw that there was always a default constructor for a new class thatyou create; you just havce the option of explicitly creating one or not. The default constructor aswe saw it doesn't take arguments: this is not a rule, it is simply assumed. Instead of a defaultconstructor, you may want to create a constructor that takes an argument. Here is an example:

Private Class Square Public Sub New(ByVal sd As Double)

End SubEnd Class

With this type of constructor, when you declare an instance of the class, you can use this newconstructor to initialize the class. Here is an example:

Public Module Exercise Private Class Square Public Sub New(ByVal sd As Double) MsgBox("Square Builder") End Sub End Class

Public Function Main() As Integer Dim sqr As Square = New Square(38.64)

Return 0 End FunctionEnd Module

If you create one constructor for your class and pass at least one argument to that constructor,the automatic default constructor created by the compiler disappears. This implies that if youdeclare an instance of the class and use the default constructor to initialize it, you would receivean error when you compile the program. Based on this, the following program will produce anerror:

Public Module Exercise Private Class Square Public Sub New(ByVal sd As Double) MsgBox("Square Builder") End Sub End Class

Public Function Main() As Integer Dim sqr As Square = New Square ' The default constructor is not available

Return 0 End FunctionEnd Module

If you still want to use the default constructor in a class after creating a constructor that takes atleast one argument, you must explicitly create that default constructor.

Practical Learning: Constructing a Class

1. To pass arguments to a constructor, change the file as follows:

Public Enum ItemCategory Women Men Girls Boys Babies Jewelry Beauty Bedroom MiscellaneousEnd Enum

Public Class StoreItem Friend ItemNumber As Long Friend Category As ItemCategory Friend ItemName As String Friend UnitPrice As Double

Public Sub New(ByVal Number As Long, _ ByVal Type As ItemCategory, _ ByVal Name As String, _ ByVal Price As Double) ItemNumber = Number Category = Type ItemName = Name UnitPrice = Price End Sub

Public Sub ShowItem() Dim StrCategory As String

Select Case Category

Page 261: Microsoft Visual Basic 2010 Tutorial

Case ItemCategory.Women StrCategory = "Women" Case ItemCategory.Men StrCategory = "Men" Case ItemCategory.Girls StrCategory = "Girls" Case ItemCategory.Boys StrCategory = "Boys" Case ItemCategory.Babies StrCategory = "Babies" Case ItemCategory.Jewelry StrCategory = "Jewelry" Case ItemCategory.Beauty StrCategory = "Beauty" Case ItemCategory.Bedroom StrCategory = "Bedroom" Case Else StrCategory = "Miscellaneous" End Select

MsgBox("=-= Department Store =-=" & vbCrLf & _ "--- Store Inventory ---" & vbCrLf & _ "Item #:" & vbTab & vbTab & ItemNumber & vbCrLf & _ "Category:" & vbTab & StrCategory & vbCrLf & _ "Item Name:" & vbTab & ItemName & vbCrLf & _ "Unit Price:" & vbTab & FormatCurrency(UnitPrice), _ MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _ "Department Store") End SubEnd Class

2. Access the DepartmentStore.vb file and change it as follows:

Public Module DepartmentStore

Public Function Main() As Integer Dim Nbr As Long Dim Classification As ItemCategory Dim Description As String Dim Value As Double Dim Item As StoreItem

Nbr = 759470 Classification = ItemCategory.Men Description = "Multistriped Organic Cotton Dress Shirt" Value = 35.5

Item = New StoreItem(Nbr, Classification, Description, Value) Item.ShowItem()

Return 0 End Function

End Module

3. Execute the application to see the result

4. Close the form and return to your programming environment

Constructor Overloading

A constructor is the primary method of a class. It allows the programmer to initialize a variable ofa class when the class is instantiated. A constructor that plays this role of initializing an instance ofa class is also called an instance constructor. Most of the time, you don't need to create aconstructor, since one is automatically provided to any class you create. Sometimes though, as wehave seen in some classes, you need to create your own constructor as you judge it necessary andsometimes, a single constructor may not be sufficient. For example, when creating a class, youmay decide, or find out, that there must be more than one way for a user to initialize a variable.

Like any other method, a constructor can be overloaded. In other words, you can create a classand give it more than one constructor. The same rules used on overloading regular methods alsoapply to constructors: the different constructors must have different number of arguments ordifferent types of arguments.

Practical Learning: Overloading a Constructor

Page 262: Microsoft Visual Basic 2010 Tutorial

1. Access the StoreItem.vb file

2. To overload the constructor, change the file as follows:

Public Enum ItemCategory Women Men Girls Boys Babies Jewelry Beauty Bedroom MiscellaneousEnd Enum

Public Class StoreItem Friend ItemNumber As Long Friend Category As ItemCategory Friend ItemName As String Friend ItemSize As String Friend UnitPrice As Double

REM Default Constructor, used to initialize an unidentified object Public Sub New() Me.ItemNumber = 0 Me.Category = ItemCategory.Miscellaneous Me.ItemName = "Unknown" Me.ItemSize = "Unknown or Fits All" Me.UnitPrice = 0D End Sub

REM This constructor is for items without size (jewelry, beauty, etc) Public Sub New(ByVal Number As Long, _ ByVal Type As ItemCategory, _ ByVal Name As String, _ ByVal Price As Double) Me.ItemNumber = Number Me.Category = Type Me.ItemName = Name Me.UnitPrice = Price End Sub

REM This constructor is used to identify an item to wear Public Sub New(ByVal Number As Long, _ ByVal Type As ItemCategory, _ ByVal Name As String, _ ByVal Size As String, _ ByVal Price As Double) Me.ItemNumber = Number Me.Category = Type Me.ItemName = Name Me.ItemSize = Size Me.UnitPrice = Price End Sub

REM This method is used to display a description of an item REM The caller will determine whether the item has a size or not Public Sub ShowItem(ByVal HasSize As Boolean) Dim StrCategory As String

Select Case Category Case ItemCategory.Women StrCategory = "Women" Case ItemCategory.Men StrCategory = "Men" Case ItemCategory.Girls StrCategory = "Girls" Case ItemCategory.Boys StrCategory = "Boys" Case ItemCategory.Babies StrCategory = "Babies" Case ItemCategory.Jewelry StrCategory = "Jewelry" Case ItemCategory.Beauty StrCategory = "Beauty" Case ItemCategory.Bedroom StrCategory = "Bedroom" Case Else StrCategory = "Miscellaneous" End Select

If HasSize = True Then MsgBox("=-= Department Store =-=" & vbCrLf & _ "--- Store Inventory ---" & vbCrLf & _ "Item #:" & vbTab & vbTab & ItemNumber & vbCrLf & _ "Category:" & vbTab & StrCategory & vbCrLf & _ "Item Name:" & vbTab & ItemName & vbCrLf & _ "Size:" & vbTab & vbTab & ItemSize & vbCrLf & _ "Unit Price:" & vbTab & FormatCurrency(UnitPrice), _ MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _ "Department Store") Else MsgBox("=-= Department Store =-=" & vbCrLf & _ "--- Store Inventory ---" & vbCrLf & _ "Item #:" & vbTab & vbTab & ItemNumber & vbCrLf & _ "Category:" & vbTab & StrCategory & vbCrLf & _ "Item Name:" & vbTab & ItemName & vbCrLf & _ "Unit Price:" & vbTab & FormatCurrency(UnitPrice), _

Page 263: Microsoft Visual Basic 2010 Tutorial

MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _ "Department Store") End If End SubEnd Class

3. Access the DepartmentStore.vb file and change it as follow:

Public Module DepartmentStore

Public Function Main() As Integer Dim Nbr As Long Dim Classification As ItemCategory Dim Description As String Dim Size As String Dim Value As Double Dim Item As StoreItem

REM Using the default constructor Item = New StoreItem Item.ShowItem(True)

Nbr = 608432 Classification = ItemCategory.Jewelry Description = "Silver 1/10-ct. T.W. Diamond Heart-Link Bracelet" Value = 95.85

REM Using the constructor that takes 4 arguments Item = New StoreItem(Nbr, Classification, Description, Value) Item.ShowItem(False)

Nbr = 437876 Classification = ItemCategory.Women Description = "Crinkled Georgette Dress" Size = "Medium" Value = 42.95

REM Using the constructor that takes 5 arguments REM after initialing a Women object Item = New StoreItem(Nbr, ItemCategory.Women, _ Description, Size, Value) Item.ShowItem(True)

REM Using the constructor that takes 5 arguments REM Directly initialing the constructor Item = New StoreItem(790475, ItemCategory.Men, _ "New Wool Comfort Pants", "36x33", 38.75) Item.ShowItem(True)

REM Using the constructor that takes 5 arguments REM Initialing the values in random order Item = New StoreItem(Type:=ItemCategory.Women, _ Size:="9 1/2 W", _ Price:=35.5, _ Name:="Modest Dress Heels", _ Number:=487046) Item.ShowItem(True)

Return 0 End Function

End Module

4. Execute the application to see the result:

Page 264: Microsoft Visual Basic 2010 Tutorial

5. Close the form and return to your programming environment

Class Destruction

Garbage Collection

When you initialize a variable using the New operator, you are in fact asking the compiler toprovide you some memory space in the heap memory. The compiler is said to "allocate" memoryfor your variable. When that variable is no longer needed, for example when your program closes,it (the variable) must be removed from memory and the space it was using can be made availableto other variables or other programs. This is referred to as garbage collection.

The .NET Framework solves the problem of garbage collection by letting the compiler "clean"memory after you. This is done automatically when the compiler judges it necessary so that theprogrammer doesn't need to worry about this issue.

Class Finalization

When you declare a variable based on a class, the compiler allocates memory for it. This portion ofmemory would be available and used while the program is running and as long as the compilerjudges this necessary. While the program is running, the instance of the class uses or consumesthe computer's resources as necessary. When the object is not needed anymore, for examplewhen the program terminates, the object must be destroyed, the memory it was using must beemptied to be made available to other programs on the computer, and the resources that theobject was using should (must) be freed to be restored to the computer so they can be used byother programs. To make this possible, the Object class is equipped with a method called Finalizethat is protected and therefore made available to all descendant classes of the .NET Framework.

The syntax of the Object.Finalize() method is:

Overrides Protected Sub Finalize()

The Finalize() method is automatically called when an instance of a class is not needed anymore.In all of the classes we have used so far, this method was transparently called when the compilerjudged that the instance of the class was not used anymore. If you don't want this method to becalled, call the

Public Shared Sub SuppressFinalize(ByVal obj As Object)

In most cases, you can let the compiler call the Finalize() method when the time comes.

Home Copyright © 2009-2010 FunctionX, Inc. Next

Page 265: Microsoft Visual Basic 2010 Tutorial

Characteristics of Members of a Class

The Fields of a Class

Constant Member Variables

We know that you can create a constant variable in your program. In the same way, you canmake a member variable of class to be constant. To do this, follow the same formula we usedpreviously to declare a constant. Here is an example:

Public Module Exercise Public Class Circle Public Radius As Double Public Const Twice As Integer = 2

Public Sub New()

End Sub End Class

Public Function Main() As Integer Dim circ As Circle Dim Diameter As Double

circ = New Circle circ.Radius = 32.86 Diameter = circ.Radius * Circle.Twice

MsgBox("Circle Characteristics" & vbCrLf & _ "Radius:" & vbTab & circ.Radius & vbCrLf & _ "Diameter:" & vbTab & Diameter)

Return 0 End FunctionEnd Module

This would produce:

Read-Only Member Variables

In the same way, in Lesson 3, we saw that you could declare a variable as ReadOnly if youwanted its value to be constant. This can also be applied to a member of a class. To do this, followthe same formula we saw for those variables, except that the variable should be made a memberof the class. Unlike a constant variable that you must initialize when creating it, you can declare aReadOnly variable in the class without initializing it. This would be done as follows:

Public ReadOnly PI As Double

After declaring the variable, you should initialize it. You can do this when declaring it, as done for aconstant. Here is an example:

Public Class Circle Public Radius As Double Public Const Twice As Integer = 2 Public ReadOnly PI As Double = 3.14159End Class

Alternatively, you can initialize the variable in the(a) constructor of its class. This would be done asfollows:

Public Module Exercise Public Class Circle Public Radius As Double Public Const Twice As Integer = 2 Public ReadOnly PI As Double

Public Sub New() PI = 3.14159 End Sub End Class

Public Function Main() As Integer Dim circ As Circle

Page 266: Microsoft Visual Basic 2010 Tutorial

Dim Diameter As Double Dim Circumference As Double

circ = New Circle circ.Radius = 32.86 Diameter = circ.Radius * Circle.Twice Circumference = Diameter * circ.PI

MsgBox("Circle Characteristics" & vbCrLf & _ "Radius:" & vbTab & vbTab & circ.Radius & vbCrLf & _ "Diameter:" & vbTab & vbTab & Diameter & vbCrLf & _ "Circumference:" & vbTab & Circumference)

Return 0 End FunctionEnd Module

This would produce:

If the value held by a read-only member variable is gotten from an expression, then the valueshould be initialized in the(a) construction with the desired expression. If you don't rightly initializeit, the compiler would initialize it with the default value based on the type of that variable.Therefore, you should make sure you initialize your ReadOnly member variables in a constructor,if those variables are based on an expression. Here are a few examples:

Public Module Exercise Public Class Circle Public Radius As Double Public Const Twice As Integer = 2 Public ReadOnly PI As Double Public ReadOnly Diameter As Double Public ReadOnly Circumference As Double Public ReadOnly Area As Double

Public Sub New() PI = 3.14159 Radius = 24.55 Diameter = Radius * Twice Circumference = Diameter * PI Area = Radius * Radius * PI End Sub End Class

Public Function Main() As Integer Dim Circ As Circle = New Circle Circ.Radius = 32.86

MsgBox("Circle Characteristics" & vbCrLf & _ "Radius:" & vbTab & vbTab & Circ.Radius & vbCrLf & _ "Diameter:" & vbTab & vbTab & Circ.Diameter & vbCrLf & _ "Circumference:" & vbTab & Circ.Circumference & vbCrLf & _ "Area:" & vbTab & vbTab & Circ.Area) Return 0 End FunctionEnd Module

This would produce:

In the previous section, we saw that a constant variable must be initialized when it is created.Although a read-only variable seems to follow the same rule, it doesn't. Remember that you don'tneed to initialize a read-only variable when you declare it since you can do this in the(a)constructor of the class. Also, because a constructor can be overloaded, a read-only membervariable can hold different values depending on the particular constructor that is accessed at aparticular time but the value of a constant variable cannot change: it is initialized once, in theclass (or in a method) and it keeps that value throughout the class (or method).

A Class as a Field

Page 267: Microsoft Visual Basic 2010 Tutorial

Just like any of the variables we have used so far, you can make a class or a structure a membervariable of another class. To use a class in your own class, of course you must have that class. Youcan use one of the classes already available in C# or you can first create your own class. Here isan example of a class:

Public Class Point Friend x As Short Friend y As ShortEnd Class

A field is a member variable created from another class instead of a primitive type. To use oneclass as a member variable of another class, simply declare its variable as you would proceed withany of the member variables we have declared so far. Here is an example:

Public Class Point Friend x As Short Friend y As ShortEnd Class

Public Class CoordinateSystem Private Start As PointEnd Class

After a class has been declared as a member variable of another class, it can be used regularly.Because the member is a class, declared as a reference, there are some rules you must follow touse it. After declaring the member variable, you must make sure you have allocated memory forit. You must also make sure that the variable is initialized appropriately before it can be used;otherwise you would receive an error when compiling the program.

Practical Learning: Using a Class as a Field

1. Start a new Console Application and name it ElectronicStore1

2. In the Solution Explorer, right-click Module1.vb and click Rename

3. Type ElectronicStore.vb and press Enter

4. To create a new class, in the Solution Explorer, right-click the name of the project, positionthe mouse on Add and click Class...

5. Set the Name to StoreItem and click Add

6. Complete the file as follows:

Public Class StoreItem Private nbr As Long Private cat As Char Private mk As String Private mdl As String Private price As Double

Public Function GetItemNumber() As Long Return nbr End Function

Public Sub SetItemNumber(ByVal number As Long) Me.nbr = number End Sub

Public Function GetCategory() As String Select Case cat Case "a", "A" Return "Audio Cables" Case "b", "B" Return "Instructional and Tutorials (Books)" Case "c", "C" Return "Cell Phones and Accessories" Case "d", "D" Return "Bags and Cases" Case "e", "E" Return "Headphones" Case "f", "F" Return "Instructional and Tutorials (VHS & DVD)" Case "g", "G" Return "Digital Cameras" Case "h", "H" Return "Cables and Connectors" Case "i", "I" Return "PDAs and Accessories" Case "j", "J" Return "Telephones and Accessories" Case "k", "K" Return "Surge Protector" Case "l", "L" Return "TVs and Videos" Case Else Return "Unknown" End Select End Function

Public Sub SetCategory(ByVal category As Char) Me.cat = category End Sub

Page 268: Microsoft Visual Basic 2010 Tutorial

Public Function GetMake() As String Return mk End Function

Public Sub SetMake(ByVal make As String) Me.mk = make End Sub

Public Function GetModel() As String Return mdl End Function

Public Sub SetModel(ByVal model As String) Me.mdl = model End Sub

Public Function GetUnitPrice() As Double

Return price End Function

Public Sub SetUnitPrice(ByVal unitPrice As Double) Me.price = unitPrice End SubEnd Class

7. Save all

Returning a Class or Passing a Class

Returning a Class From a Method

Like a value from a regular type, you can return a class value from a method of a class. To dothis, you can first declare the method and specify the class as the return type. Here is anexample:

Public Class Point Friend x As Short Friend y As ShortEnd Class

Public Class CoordinateSystem Private PtStart As Point Private PtEnd As Point

Public Function GetThePoint() As Point

End FunctionEnd Class

After implementing the method, you must return a value that is conform to the class, otherwiseyou would receive an error when compiling the application. You can proceed by declaring a variableof the class in the body of the method, initializing the variable, and then returning it. Here is anexample:

Public Class Point Friend x As Short Friend y As ShortEnd Class

Public Class CoordinateSystem Private PtStart As Point Private PtEnd As Point

Public Function GetThePoint() As Point Dim Pt As Point = New Point

Pt.x = CShort(InputBox("Enter the x coordinate of the point: ")) Pt.y = CShort(InputBox("Enter the y coordinate of the point: "))

Return Pt End FunctionEnd Class

Once a method has returned a value of a class, the value can be used as normally as possible.Here is an example:

Public Module Exercise Public Class Point Friend x As Short Friend y As Short End Class

Public Class CoordinateSystem Private PtStart As Point Private PtEnd As Point

Public Function GetThePoint() As Point Dim Pt As Point = New Point

Page 269: Microsoft Visual Basic 2010 Tutorial

Pt.x = CShort(InputBox("Enter the x coordinate of the point: ")) Pt.y = CShort(InputBox("Enter the y coordinate of the point: "))

Return Pt End Function End Class

Public Function Main() As Integer Dim Coordinate As Point Dim Coordinator As CoordinateSystem

Coordinator = New CoordinateSystem Coordinate = Coordinator.GetThePoint()

Return 0 End FunctionEnd Module

Passing a Class as Argument

Once a class has been created, it can be used like any other variable. For example, its variable canbe passed as argument to a procedure or to a method of another class. When a class is passed asargument:

Its public members are available to procedures and classes of its project and procedures andclasses of o ther projects

Its friendly members are available to the procedures and classes of the same project

As done for the arguments of primitive types, in the body of the procedure gets the argument,access its public or friendly members and use them as you see fit. Here is an example:

Public Module Exercise Public Class Point Friend x As Short Friend y As Short End Class

Public Class CoordinateSystem Private PtStart As Point Private PtEnd As Point

Public Function GetThePoint() As Point Dim Pt As Point = New Point

Pt.x = CShort(InputBox("Enter the x coordinate of the point: ")) Pt.y = CShort(InputBox("Enter the y coordinate of the point: "))

Return Pt End Function

Public Sub ShowThePoint(ByVal Coord As Point) MsgBox("Point Coordinate P(" & Coord.x & ", " & Coord.y & ")") End Sub End Class

Public Function Main() As Integer Dim Coordinate As Point Dim Coordinator As CoordinateSystem

Coordinator = New CoordinateSystem Coordinate = Coordinator.GetThePoint() Coordinator.ShowThePoint(Coordinate) Return 0 End FunctionEnd Module

Here is an example of running the program:

Page 270: Microsoft Visual Basic 2010 Tutorial

As done for the arguments of primitive types, you can pass more than one class as argument to amethod.

Because classes are always used as references, when passing a class as argument, it is implied tobe passed by reference. To reinforce this, you can type the ByRef keyword to the left of theargument. Here are examples:

Public Module Exercise Public Class Point Friend x As Short Friend y As Short End Class

Public Class CoordinateSystem Private PtStart As Point Private PtEnd As Point

Public Function GetThePoint() As Point Dim Pt As Point = New Point

Pt.x = CShort(InputBox("Enter the x coordinate of the point: ")) Pt.y = CShort(InputBox("Enter the y coordinate of the point: "))

Return Pt End Function

Public Sub ShowTheLine(ByRef StartPoint As Point, _ ByRef EndPoint As Point) MsgBox("Line Characteristics: The line goes from P(" & _ StartPoint.x & ", " & StartPoint.y & ") to Q(" & _ EndPoint.x & ", " & EndPoint.y & ")") End Sub End Class

Public Function Main() As Integer Dim First, Second As Point Dim Coordinator As CoordinateSystem

Coordinator = New CoordinateSystem First = Coordinator.GetThePoint() Second = Coordinator.GetThePoint()

Coordinator.ShowTheLine(First, Second) Return 0 End FunctionEnd Module

Practical Learning: Returning a Class or Passing One as Argument

1. To return a class or pass it as argument, change the ElectronicStore.vb file as follows:

Public Module ElectronicStore Dim DiscountAmount As Double Dim NetPrice As Double Dim Quantity As Integer Dim SaleTotal As Double

Public Function GetDiscountRate() As Double Dim Discount As Double

Discount = _ CDbl(InputBox("Discount Applied (Enter 0 to 100, 0 if no discount): "))

Return Discount End Function

Public Function GetQuantity() As Integer Dim q As Integer

q = CInt(inputbox("Enter Quantity: ")) Return q End Function

Public Function Create() As StoreItem Dim ItemNumber As Long Dim Category As Char Dim Make As String Dim Model As String Dim Price As Double Dim SaleItem As StoreItem = New StoreItem

ItemNumber = CLng(InputBox("Enter the Item #", "Nearson Electonics"))

Category = CChar(InputBox("Category" & vbCrLf & _

Page 271: Microsoft Visual Basic 2010 Tutorial

"A - Audio Cables" & vbCrLf & _ "B - Instructional and Tutorials (Books)" & vbCrLf & _ "C - Cell Phones and Accessories" & vbCrLf & _ "D - Bags and Cases" & vbCrLf & _ "E - Headphones" & vbCrLf & _ "F - Instructional and Tutorials (VHS & DVD)" & vbCrLf & _ "G - Digital Cameras" & vbCrLf & _ "H - Cables and Connectors" & vbCrLf & _ "I - PDAs and Accessories" & vbCrLf & _ "J - Telephones and Accessories" & vbCrLf & _ "K - Surge Protector" & vbCrLf & _ "L - TVs and Videos" & vbCrLf & _ "Enter Your Choice:", "Nearson Electonics")) Make = InputBox("Enter Make", "Nearson Electonics") Model = InputBox("Enter Model", "Nearson Electonics") Price = CDbl(InputBox("Enter Unit Price:", "Nearson Electonics"))

SaleItem.SetItemNumber(ItemNumber) SaleItem.SetCategory(Category) SaleItem.SetMake(Make) SaleItem.SetModel(Model) SaleItem.SetUnitPrice(Price)

Return SaleItem End Function

Public Sub ShowSaleItem(ByVal item As StoreItem) Dim discountRate As Double = GetDiscountRate()

Quantity = CInt(GetQuantity()) DiscountAmount = item.GetUnitPrice() * discountRate / 100 NetPrice = item.GetUnitPrice() - DiscountAmount SaleTotal = NetPrice * Quantity

MsgBox("=-= Nearson Electonics =-=" & vbCrLf & _ "Store Item Description" & vbCrLf & _ "Item Number:" & vbTab & item.GetItemNumber() & vbCrLf & _ "Category:" & vbTab & item.GetCategory() & vbCrLf & _ "Make:" & vbTab & vbTab & item.GetMake() & vbCrLf & _ "Model:" & vbTab & vbTab & item.GetModel() & vbCrLf & _ "Unit Price:" & vbTab & _ FormatCurrency(item.GetUnitPrice()) & vbCrLf & _ "Discount Rate:" & vbTab & _ FormatPercent(discountRate / 100) & vbCrLf & _ "Discount Amount:" & vbTab & _ FormatCurrency(DiscountAmount) & vbCrLf & _ "Price/Item:" & vbTab & FormatCurrency(NetPrice) & vbCrLf & _ "Quantity: " & vbTab & Quantity & vbCrLf & _ "Sale Total: " & vbTab & FormatCurrency(SaleTotal), _ MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _ "Nearson Electonics") End Sub

Public Function Main() As Integer Dim Item As StoreItem = New StoreItem()

Item = Create() ShowSaleItem(Item)

End Function

End Module

2. Execute the application to test it

3. Enter the item information as follows: Item # 917305

Category e

Make Sennheiser

Model HD280 Pro Closed-Back Headphones

Unit Price 99.95

Discount 20

Quantity 4

Page 272: Microsoft Visual Basic 2010 Tutorial

4. Return to your programming environment

Involving a Class and its Own Methods

Passing a Class as its Own Argument

An instance of a class can be passed as an argument to one of its own methods (if you haveprogrammed in C++, an example of this implementation is the copy constructor; although you canlegitimately create a copy constructor in C#, it does not have the exact same concept as in C++,probably because C# has the Equals() method, which is actually a concept of the .NETFramework). To do this, you primarily pass the argument as if it were any class. Here is anexample:

Public Class Point Friend x As Integer Friend y As Integer

Public Sub Equivalent(ByVal Same As Point)

End SubEnd Class

Then, in the body of the method, do whatever you want. You can, or you may not, use theargument. Still, if you decide to use the argument, know that all of the other members of theclass are available through the argument. Probably the simplest way to use the argument is theassign each of of its values to the equivalent member of the class. Here is an example:

Public Class Point Friend x As Integer Friend y As Integer

Public Sub Equivalent(ByVal Same As Point) Me.x = Same.x Me.y = Same.y End SubEnd Class

When calling the method, make sure you pass an instance of the class to it. You can first createand define the class, then pass it. Here is an example:

Public Module Exercise Public Class Point Friend x As Integer Friend y As Integer

Public Sub Equivalent(ByVal Same As Point)

Page 273: Microsoft Visual Basic 2010 Tutorial

Me.x = Same.x Me.y = Same.y End Sub End Class

Public Sub ShowPoint(ByVal Coord As Point) MsgBox("Point Coordinate: P(" & Coord.x & ", " & Coord.y & ")") End Sub

Public Function Main() As Integer Dim Pt As Point = New Point

Pt.x = 4 Pt.y = 6 ShowPoint(Pt)

Dim One As Point = New Point One.Equivalent(Pt)

ShowPoint(One) Return 0 End FunctionEnd Module

This would produce:

Instead of first declaring a variable of the class and initializing it, you can create an instance of theclass in the parentheses of the calling method. To do this, you may need a constructor that canspecify the values of the fields of the class so the argument can be rightfully initialized. Here is anexample:

Public Module Exercise Public Class Point Friend x As Integer Friend y As Integer

Public Sub New()

End Sub

Public Sub New(ByVal XCoord As Integer, ByVal YCoord As Integer) Me.x = XCoord Me.y = YCoord End Sub

Public Sub Equivalent(ByVal Same As Point) Me.x = Same.x Me.y = Same.y End Sub End Class

Public Sub ShowPoint(ByVal Coord As Point) MsgBox("Point Coordinate: P(" & Coord.x & ", " & Coord.y & ")") End Sub

Public Function Main() As Integer Dim Pt As Point = New Point

Pt.x = 4 Pt.y = 6 ShowPoint(Pt)

Dim One As Point = New Point One.Equivalent(New Point(-3, 2)) ShowPoint(One)

Return 0 End FunctionEnd Module

This would produce:

Page 274: Microsoft Visual Basic 2010 Tutorial

Instead of a formal method, you can use a constructor of the class to pass an instance of thesame class. Then, in the constructor, use the argument as you see fit, knowing that all themembers of the class are available. Here is an example:

Public Class Point Friend x As Integer Friend y As Integer

Public Sub New()

End Sub

Public Sub New(ByVal XCoord As Integer, ByVal YCoord As Integer) Me.x = XCoord Me.y = YCoord End Sub

Public Sub New(ByVal Same As Point) Me.x = Same.x Me.y = Same.y End SubEnd Class

Obviously the purpose of passing a class to one of its own methods is not to find its equivalent.The C# language (actually the .NET Framework) can also take care of that (through the Equals()built-in method). Instead, you can create a method that takes an instance of the same class butmodifies that instance. For example, for our Point class, we may want to create a new point that isdistanced by one unit from the current Point object. Here is an example of doing that:

Public Module Exercise Public Class Point Friend x As Integer Friend y As Integer

Public Sub New()

End Sub

Public Sub New(ByVal XCoord As Integer, ByVal YCoord As Integer) Me.x = XCoord Me.y = YCoord End Sub

Public Sub Equivalent(ByVal Same As Point) Me.x = Same.x Me.y = Same.y End Sub

Public Sub CreatePointOneUnitAway(ByVal AddUnit As Point) Me.x = AddUnit.x + 1 Me.y = AddUnit.y + 1 End Sub End Class

Public Sub ShowPoint(ByVal Coord As Point) MsgBox("Point Coordinate: P(" & Coord.x & ", " & Coord.y & ")") End Sub

Public Function Main() As Integer Dim Pt As Point = New Point

Pt.x = 4 Pt.y = 6

Dim One As Point = New Point One.CreatePointOneUnitAway(Pt) ShowPoint(One) One.CreatePointOneUnitAway(New Point(-8, -3)) ShowPoint(One)

Return 0 End FunctionEnd Module

This would produce:

Page 275: Microsoft Visual Basic 2010 Tutorial

Returning a Class From its Own Method

You can create a method in a class that returns an instance of the class. To start, on the left sideof the method, enter the name of the class. Here is an example:

Public Class Point Public Function MethodName() As Point

End FunctionEnd Class

There are various ways you can deal with the method. If you want to return a new value of theclass, you can declare an instance of the class, initialize it, and then return it. Here is an example:

Public Module Exercise Public Class Point Friend x As Integer Friend y As Integer

Public Sub New()

End Sub

Public Sub New(ByVal XCoord As Integer, ByVal YCoord As Integer) Me.x = XCoord Me.y = YCoord End Sub

Public Sub New(ByVal Same As Point) Me.x = Same.x Me.x = Same.x End Sub

Public Function AdvanceBy5() As Point Dim Some As Point = New Point Some.x = 5 Some.y = 5 Return Some End Function End Class

Public Sub ShowPoint(ByVal Coord As Point) MsgBox("Point Coordinate: P(" & Coord.x & ", " & Coord.y & ")") End Sub

Public Function Main() As Integer Dim Pt As Point = New Point

Pt.x = 4 Pt.y = 6 ShowPoint(Pt)

Dim Away5 As Point = Pt.AdvanceBy5() ShowPoint(Away5)

Return 0 End FunctionEnd Module

This would produce:

Alternatively, you can declare an instance of the class, use the current values of the classcombined with the those of the instance to get new values, and then return the instance.

Remember that, to call a method, if it is not static, you will need to declare an instance of theclass from where you are calling the method. The second type of implementation consists ofmodifying the instance of the class that is calling the method. For example, you can add values toits fields or you can perform any other operation you want on the members of the calling instance.is an example:

Page 276: Microsoft Visual Basic 2010 Tutorial

Public Module Exercise Public Class Point Friend x As Integer Friend y As Integer

Public Sub New()

End Sub

Public Sub New(ByVal XCoord As Integer, ByVal YCoord As Integer)

Me.x = XCoord Me.y = YCoord End Sub

Public Sub New(ByVal Same As Point)

Me.x = Same.x Me.x = Same.x End Sub

REM This method adds 1 to each field of the class REM to get a new point away North-East of the current point Public Function CreatePointOneUnitAway() As Point Me.x = Me.x + 1 Me.y = Me.y + 1

Return Me End Function End Class

Public Sub ShowPoint(ByVal Coord As Point) MsgBox("Point Coordinate: P(" & Coord.x & ", " & Coord.y & ")") End Sub

Public Function Main() As Integer Dim Pt As Point = New Point

Pt.x = 4 Pt.y = 6

ShowPoint(Pt)

Dim One As Point = New Point(-8, 5) Dim Another As Point = One.CreatePointOneUnitAway() ShowPoint(Another)

Return 0 End FunctionEnd Module

This would produce:

As we have learned now, you can create a method that takes an argument that is the same typeas its parent class. In the method, you can access any member of the class, including calling theother methods of the class.

Home Copyright © 2008-2010 FunctionX

Page 277: Microsoft Visual Basic 2010 Tutorial

The Shared Members of a Class

Shared Member Variables

When you declare a variable of a class, you are said to have created an instance of the class.This makes an object available so you can initialize and use its member variables and methods asyou see fit. Just as you can declare one instance of a class, in the same way, you can declare asmany instances as you judge it necessary.

After declaring various variables of the same class and initializing them, each variable has andkeeps its own values. Here is an example:

Public Module Exercise Friend Class Rectangle Public Length As Double Public Height As Double

Public Function CalculatePerimeter#() Return (Length + Height) * 2 End Function

Public Function CalcaulteArea#() Return Length * Height End Function End Class

Public Function Main() As Integer Dim RegistrationCard As New Rectangle Dim Invoice As New Rectangle

RegistrationCard.Length = 24.55 : RegistrationCard.Height = 20.68 Invoice.Length = 8.5 : Invoice.Height = 11.65

MsgBox("==========================" & vbCrLf & _ "=-= Paper Registration Characteristics =-=" & vbCrLf & _ "Length: " & vbTab & vbTab & RegistrationCard.Length & vbCrLf & _ "Height: " & vbTab & vbTab & RegistrationCard.Height & vbCrLf & _ "Perimeter: " & vbTab & _ RegistrationCard.CalculatePerimeter#() & vbCrLf & _ "Area: " & vbTab & vbTab & _ RegistrationCard.CalcaulteArea#() & vbCrLf & _ "----------------------------------------------------" & vbCrLf & _ "=-= Paper Registration Characteristics =-=" & vbCrLf & _ "Length: " & vbTab & vbTab & Invoice.Length & vbCrLf & _ "Height: " & vbTab & vbTab & Invoice.Height & vbCrLf & _ "Perimeter: " & vbTab & Invoice.CalculatePerimeter#() & vbCrLf & _ "Area: " & vbTab & vbTab & Invoice.CalcaulteArea#() & vbCrLf & _ "==========================") Return 0 End Function

End Module

This would produce:

In order to access the member variables of the above Rectangle class, you must declare a variableof the class. The Visual Basic language provides an alternative. You can declare a member variableso that you can access it from anywhere in your code without primarily declaring a variable of theclass. In order to have such a member variable, you must explicitly create it as shared.

To create a shared member variable, type the Shared keyword on its left when declaring it. Afterthe shared member variable has been declared, you can use it like any other member variable of

Page 278: Microsoft Visual Basic 2010 Tutorial

that class, except that you don't need to declare an instance of that class when you want toaccess that member variable. Here is an example:

Public Module Exercise Friend Class Rectangle Public Length As Double Public Shared Height As Double

Public Function CalculatePerimeter#() Return (Length + Height) * 2 End Function

Public Function CalcaulteArea#() Return Length * Height End Function End Class

Public Function Main() As Integer REM Notice that a Rectangle variable is not declared Rectangle.Height = 20.68

MsgBox("Rectangle Characteristics" & vbCrLf & _ "Height:" & vbTab & vbTab & Rectangle.Height)

Return 0 End FunctionEnd Module

This would produce:

Based on this, when creating a class, you will decide whether you want a particular membervariable to be shared or not. You can have only one, two, more, or all member variables shared ina class. Experience and your own goal will guide you.

Shared Methods

Consider the following class:

Public Module Exercise Friend Class Rectangle Public Shared Length As Double Public Shared Height As Double

Public Function CalculatePerimeter#() Return (Length + Height) * 2 End Function

Public Function CalcaulteArea#() Return Length * Height End Function End Class

Public Function Main() As Integer REM Notice that a Rectangle variable is not declared Rectangle.Height = 20.68 Rectangle.Length = 32.47

MsgBox("Rectangle Characteristics" & vbCrLf & _ "Length:" & vbTab & Rectangle.Length & vbCrLf & _ "Height:" & vbTab & Rectangle.Height) Return 0 End Function

End Module

This would produce:

Like member variables, a method can be shared among classes. In some cases, shared methodsare more used than shared member variables because a shared method allows performing anaction on a class without declaring an instance of that class. To create a shared method, type theShared keyword on the left of the Sub or the Function keyword. Here is an example:

Page 279: Microsoft Visual Basic 2010 Tutorial

Here is an example:

Friend Class Rectangle Shared Function CalculatePerimeter#() Return (Length + Height) * 2 End FunctionEnd Class

You can apply the access modifier on the method as we have done so far. Here are examples:

Friend Class Rectangle Public Shared Function CalculatePerimeter#()

End Function

Public Shared Function CalcaulteArea#()

End FunctionEnd Class

Like a shared member variable, once a method has been created as shared, it can be accesseddirectly from anywhere. Remember that you would need to type the name of the class beforeaccessing the method. The name of the class allows you to "qualify" the method. Here is anexample:

Public Module Exercise Friend Class Rectangle Public Shared Length As Double Public Shared Height As Double

Public Shared Function CalculatePerimeter#() Return (Length + Height) * 2 End Function

Public Shared Function CalcaulteArea#() Return Length * Height End Function End Class

Public Function Main() As Integer REM Notice that a Rectangle variable is not declared Rectangle.Height = 20.68 Rectangle.Length = 32.47

MsgBox("Rectangle Characteristics" & vbCrLf & _ "Length:" & vbTab & vbTab & Rectangle.Length & vbCrLf & _ "Height:" & vbTab & vbTab & Rectangle.Height & vbCrLf & _ "Perimeter: " & vbTab & Rectangle.CalculatePerimeter#() & vbCrLf & _ "Area: " & vbTab & vbTab & Rectangle.CalcaulteArea#()) Return 0 End Function

End Module

Home Copyright © 2009-2010 FunctionX, Inc.

Page 280: Microsoft Visual Basic 2010 Tutorial

Characteristics of Members of a Class

The Fields of a Class

Constant Member Variables

We know that you can create a constant variable in your program. In the same way, you canmake a member variable of class to be constant. To do this, follow the same formula we usedpreviously to declare a constant. Here is an example:

Public Module Exercise Public Class Circle Public Radius As Double Public Const Twice As Integer = 2

Public Sub New()

End Sub End Class

Public Function Main() As Integer Dim circ As Circle Dim Diameter As Double

circ = New Circle circ.Radius = 32.86 Diameter = circ.Radius * Circle.Twice

MsgBox("Circle Characteristics" & vbCrLf & _ "Radius:" & vbTab & circ.Radius & vbCrLf & _ "Diameter:" & vbTab & Diameter)

Return 0 End FunctionEnd Module

This would produce:

Read-Only Member Variables

In the same way, in Lesson 3, we saw that you could declare a variable as ReadOnly if youwanted its value to be constant. This can also be applied to a member of a class. To do this, followthe same formula we saw for those variables, except that the variable should be made a memberof the class. Unlike a constant variable that you must initialize when creating it, you can declare aReadOnly variable in the class without initializing it. This would be done as follows:

Public ReadOnly PI As Double

After declaring the variable, you should initialize it. You can do this when declaring it, as done for aconstant. Here is an example:

Public Class Circle Public Radius As Double Public Const Twice As Integer = 2 Public ReadOnly PI As Double = 3.14159End Class

Alternatively, you can initialize the variable in the(a) constructor of its class. This would be done asfollows:

Public Module Exercise Public Class Circle Public Radius As Double Public Const Twice As Integer = 2 Public ReadOnly PI As Double

Public Sub New() PI = 3.14159 End Sub End Class

Public Function Main() As Integer Dim circ As Circle

Page 281: Microsoft Visual Basic 2010 Tutorial

Dim Diameter As Double Dim Circumference As Double

circ = New Circle circ.Radius = 32.86 Diameter = circ.Radius * Circle.Twice Circumference = Diameter * circ.PI

MsgBox("Circle Characteristics" & vbCrLf & _ "Radius:" & vbTab & vbTab & circ.Radius & vbCrLf & _ "Diameter:" & vbTab & vbTab & Diameter & vbCrLf & _ "Circumference:" & vbTab & Circumference)

Return 0 End FunctionEnd Module

This would produce:

If the value held by a read-only member variable is gotten from an expression, then the valueshould be initialized in the(a) construction with the desired expression. If you don't rightly initializeit, the compiler would initialize it with the default value based on the type of that variable.Therefore, you should make sure you initialize your ReadOnly member variables in a constructor,if those variables are based on an expression. Here are a few examples:

Public Module Exercise Public Class Circle Public Radius As Double Public Const Twice As Integer = 2 Public ReadOnly PI As Double Public ReadOnly Diameter As Double Public ReadOnly Circumference As Double Public ReadOnly Area As Double

Public Sub New() PI = 3.14159 Radius = 24.55 Diameter = Radius * Twice Circumference = Diameter * PI Area = Radius * Radius * PI End Sub End Class

Public Function Main() As Integer Dim Circ As Circle = New Circle Circ.Radius = 32.86

MsgBox("Circle Characteristics" & vbCrLf & _ "Radius:" & vbTab & vbTab & Circ.Radius & vbCrLf & _ "Diameter:" & vbTab & vbTab & Circ.Diameter & vbCrLf & _ "Circumference:" & vbTab & Circ.Circumference & vbCrLf & _ "Area:" & vbTab & vbTab & Circ.Area) Return 0 End FunctionEnd Module

This would produce:

In the previous section, we saw that a constant variable must be initialized when it is created.Although a read-only variable seems to follow the same rule, it doesn't. Remember that you don'tneed to initialize a read-only variable when you declare it since you can do this in the(a)constructor of the class. Also, because a constructor can be overloaded, a read-only membervariable can hold different values depending on the particular constructor that is accessed at aparticular time but the value of a constant variable cannot change: it is initialized once, in theclass (or in a method) and it keeps that value throughout the class (or method).

A Class as a Field

Page 282: Microsoft Visual Basic 2010 Tutorial

Just like any of the variables we have used so far, you can make a class or a structure a membervariable of another class. To use a class in your own class, of course you must have that class. Youcan use one of the classes already available in C# or you can first create your own class. Here isan example of a class:

Public Class Point Friend x As Short Friend y As ShortEnd Class

A field is a member variable created from another class instead of a primitive type. To use oneclass as a member variable of another class, simply declare its variable as you would proceed withany of the member variables we have declared so far. Here is an example:

Public Class Point Friend x As Short Friend y As ShortEnd Class

Public Class CoordinateSystem Private Start As PointEnd Class

After a class has been declared as a member variable of another class, it can be used regularly.Because the member is a class, declared as a reference, there are some rules you must follow touse it. After declaring the member variable, you must make sure you have allocated memory forit. You must also make sure that the variable is initialized appropriately before it can be used;otherwise you would receive an error when compiling the program.

Practical Learning: Using a Class as a Field

1. Start a new Console Application and name it ElectronicStore1

2. In the Solution Explorer, right-click Module1.vb and click Rename

3. Type ElectronicStore.vb and press Enter

4. To create a new class, in the Solution Explorer, right-click the name of the project, positionthe mouse on Add and click Class...

5. Set the Name to StoreItem and click Add

6. Complete the file as follows:

Public Class StoreItem Private nbr As Long Private cat As Char Private mk As String Private mdl As String Private price As Double

Public Function GetItemNumber() As Long Return nbr End Function

Public Sub SetItemNumber(ByVal number As Long) Me.nbr = number End Sub

Public Function GetCategory() As String Select Case cat Case "a", "A" Return "Audio Cables" Case "b", "B" Return "Instructional and Tutorials (Books)" Case "c", "C" Return "Cell Phones and Accessories" Case "d", "D" Return "Bags and Cases" Case "e", "E" Return "Headphones" Case "f", "F" Return "Instructional and Tutorials (VHS & DVD)" Case "g", "G" Return "Digital Cameras" Case "h", "H" Return "Cables and Connectors" Case "i", "I" Return "PDAs and Accessories" Case "j", "J" Return "Telephones and Accessories" Case "k", "K" Return "Surge Protector" Case "l", "L" Return "TVs and Videos" Case Else Return "Unknown" End Select End Function

Public Sub SetCategory(ByVal category As Char) Me.cat = category End Sub

Page 283: Microsoft Visual Basic 2010 Tutorial

Public Function GetMake() As String Return mk End Function

Public Sub SetMake(ByVal make As String) Me.mk = make End Sub

Public Function GetModel() As String Return mdl End Function

Public Sub SetModel(ByVal model As String) Me.mdl = model End Sub

Public Function GetUnitPrice() As Double

Return price End Function

Public Sub SetUnitPrice(ByVal unitPrice As Double) Me.price = unitPrice End SubEnd Class

7. Save all

Returning a Class or Passing a Class

Returning a Class From a Method

Like a value from a regular type, you can return a class value from a method of a class. To dothis, you can first declare the method and specify the class as the return type. Here is anexample:

Public Class Point Friend x As Short Friend y As ShortEnd Class

Public Class CoordinateSystem Private PtStart As Point Private PtEnd As Point

Public Function GetThePoint() As Point

End FunctionEnd Class

After implementing the method, you must return a value that is conform to the class, otherwiseyou would receive an error when compiling the application. You can proceed by declaring a variableof the class in the body of the method, initializing the variable, and then returning it. Here is anexample:

Public Class Point Friend x As Short Friend y As ShortEnd Class

Public Class CoordinateSystem Private PtStart As Point Private PtEnd As Point

Public Function GetThePoint() As Point Dim Pt As Point = New Point

Pt.x = CShort(InputBox("Enter the x coordinate of the point: ")) Pt.y = CShort(InputBox("Enter the y coordinate of the point: "))

Return Pt End FunctionEnd Class

Once a method has returned a value of a class, the value can be used as normally as possible.Here is an example:

Public Module Exercise Public Class Point Friend x As Short Friend y As Short End Class

Public Class CoordinateSystem Private PtStart As Point Private PtEnd As Point

Public Function GetThePoint() As Point Dim Pt As Point = New Point

Page 284: Microsoft Visual Basic 2010 Tutorial

Pt.x = CShort(InputBox("Enter the x coordinate of the point: ")) Pt.y = CShort(InputBox("Enter the y coordinate of the point: "))

Return Pt End Function End Class

Public Function Main() As Integer Dim Coordinate As Point Dim Coordinator As CoordinateSystem

Coordinator = New CoordinateSystem Coordinate = Coordinator.GetThePoint()

Return 0 End FunctionEnd Module

Passing a Class as Argument

Once a class has been created, it can be used like any other variable. For example, its variable canbe passed as argument to a procedure or to a method of another class. When a class is passed asargument:

Its public members are available to procedures and classes of its project and procedures andclasses of o ther projects

Its friendly members are available to the procedures and classes of the same project

As done for the arguments of primitive types, in the body of the procedure gets the argument,access its public or friendly members and use them as you see fit. Here is an example:

Public Module Exercise Public Class Point Friend x As Short Friend y As Short End Class

Public Class CoordinateSystem Private PtStart As Point Private PtEnd As Point

Public Function GetThePoint() As Point Dim Pt As Point = New Point

Pt.x = CShort(InputBox("Enter the x coordinate of the point: ")) Pt.y = CShort(InputBox("Enter the y coordinate of the point: "))

Return Pt End Function

Public Sub ShowThePoint(ByVal Coord As Point) MsgBox("Point Coordinate P(" & Coord.x & ", " & Coord.y & ")") End Sub End Class

Public Function Main() As Integer Dim Coordinate As Point Dim Coordinator As CoordinateSystem

Coordinator = New CoordinateSystem Coordinate = Coordinator.GetThePoint() Coordinator.ShowThePoint(Coordinate) Return 0 End FunctionEnd Module

Here is an example of running the program:

Page 285: Microsoft Visual Basic 2010 Tutorial

As done for the arguments of primitive types, you can pass more than one class as argument to amethod.

Because classes are always used as references, when passing a class as argument, it is implied tobe passed by reference. To reinforce this, you can type the ByRef keyword to the left of theargument. Here are examples:

Public Module Exercise Public Class Point Friend x As Short Friend y As Short End Class

Public Class CoordinateSystem Private PtStart As Point Private PtEnd As Point

Public Function GetThePoint() As Point Dim Pt As Point = New Point

Pt.x = CShort(InputBox("Enter the x coordinate of the point: ")) Pt.y = CShort(InputBox("Enter the y coordinate of the point: "))

Return Pt End Function

Public Sub ShowTheLine(ByRef StartPoint As Point, _ ByRef EndPoint As Point) MsgBox("Line Characteristics: The line goes from P(" & _ StartPoint.x & ", " & StartPoint.y & ") to Q(" & _ EndPoint.x & ", " & EndPoint.y & ")") End Sub End Class

Public Function Main() As Integer Dim First, Second As Point Dim Coordinator As CoordinateSystem

Coordinator = New CoordinateSystem First = Coordinator.GetThePoint() Second = Coordinator.GetThePoint()

Coordinator.ShowTheLine(First, Second) Return 0 End FunctionEnd Module

Practical Learning: Returning a Class or Passing One as Argument

1. To return a class or pass it as argument, change the ElectronicStore.vb file as follows:

Public Module ElectronicStore Dim DiscountAmount As Double Dim NetPrice As Double Dim Quantity As Integer Dim SaleTotal As Double

Public Function GetDiscountRate() As Double Dim Discount As Double

Discount = _ CDbl(InputBox("Discount Applied (Enter 0 to 100, 0 if no discount): "))

Return Discount End Function

Public Function GetQuantity() As Integer Dim q As Integer

q = CInt(inputbox("Enter Quantity: ")) Return q End Function

Public Function Create() As StoreItem Dim ItemNumber As Long Dim Category As Char Dim Make As String Dim Model As String Dim Price As Double Dim SaleItem As StoreItem = New StoreItem

ItemNumber = CLng(InputBox("Enter the Item #", "Nearson Electonics"))

Category = CChar(InputBox("Category" & vbCrLf & _

Page 286: Microsoft Visual Basic 2010 Tutorial

"A - Audio Cables" & vbCrLf & _ "B - Instructional and Tutorials (Books)" & vbCrLf & _ "C - Cell Phones and Accessories" & vbCrLf & _ "D - Bags and Cases" & vbCrLf & _ "E - Headphones" & vbCrLf & _ "F - Instructional and Tutorials (VHS & DVD)" & vbCrLf & _ "G - Digital Cameras" & vbCrLf & _ "H - Cables and Connectors" & vbCrLf & _ "I - PDAs and Accessories" & vbCrLf & _ "J - Telephones and Accessories" & vbCrLf & _ "K - Surge Protector" & vbCrLf & _ "L - TVs and Videos" & vbCrLf & _ "Enter Your Choice:", "Nearson Electonics")) Make = InputBox("Enter Make", "Nearson Electonics") Model = InputBox("Enter Model", "Nearson Electonics") Price = CDbl(InputBox("Enter Unit Price:", "Nearson Electonics"))

SaleItem.SetItemNumber(ItemNumber) SaleItem.SetCategory(Category) SaleItem.SetMake(Make) SaleItem.SetModel(Model) SaleItem.SetUnitPrice(Price)

Return SaleItem End Function

Public Sub ShowSaleItem(ByVal item As StoreItem) Dim discountRate As Double = GetDiscountRate()

Quantity = CInt(GetQuantity()) DiscountAmount = item.GetUnitPrice() * discountRate / 100 NetPrice = item.GetUnitPrice() - DiscountAmount SaleTotal = NetPrice * Quantity

MsgBox("=-= Nearson Electonics =-=" & vbCrLf & _ "Store Item Description" & vbCrLf & _ "Item Number:" & vbTab & item.GetItemNumber() & vbCrLf & _ "Category:" & vbTab & item.GetCategory() & vbCrLf & _ "Make:" & vbTab & vbTab & item.GetMake() & vbCrLf & _ "Model:" & vbTab & vbTab & item.GetModel() & vbCrLf & _ "Unit Price:" & vbTab & _ FormatCurrency(item.GetUnitPrice()) & vbCrLf & _ "Discount Rate:" & vbTab & _ FormatPercent(discountRate / 100) & vbCrLf & _ "Discount Amount:" & vbTab & _ FormatCurrency(DiscountAmount) & vbCrLf & _ "Price/Item:" & vbTab & FormatCurrency(NetPrice) & vbCrLf & _ "Quantity: " & vbTab & Quantity & vbCrLf & _ "Sale Total: " & vbTab & FormatCurrency(SaleTotal), _ MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _ "Nearson Electonics") End Sub

Public Function Main() As Integer Dim Item As StoreItem = New StoreItem()

Item = Create() ShowSaleItem(Item)

End Function

End Module

2. Execute the application to test it

3. Enter the item information as follows: Item # 917305

Category e

Make Sennheiser

Model HD280 Pro Closed-Back Headphones

Unit Price 99.95

Discount 20

Quantity 4

Page 287: Microsoft Visual Basic 2010 Tutorial

4. Return to your programming environment

Involving a Class and its Own Methods

Passing a Class as its Own Argument

An instance of a class can be passed as an argument to one of its own methods (if you haveprogrammed in C++, an example of this implementation is the copy constructor; although you canlegitimately create a copy constructor in C#, it does not have the exact same concept as in C++,probably because C# has the Equals() method, which is actually a concept of the .NETFramework). To do this, you primarily pass the argument as if it were any class. Here is anexample:

Public Class Point Friend x As Integer Friend y As Integer

Public Sub Equivalent(ByVal Same As Point)

End SubEnd Class

Then, in the body of the method, do whatever you want. You can, or you may not, use theargument. Still, if you decide to use the argument, know that all of the other members of theclass are available through the argument. Probably the simplest way to use the argument is theassign each of of its values to the equivalent member of the class. Here is an example:

Public Class Point Friend x As Integer Friend y As Integer

Public Sub Equivalent(ByVal Same As Point) Me.x = Same.x Me.y = Same.y End SubEnd Class

When calling the method, make sure you pass an instance of the class to it. You can first createand define the class, then pass it. Here is an example:

Public Module Exercise Public Class Point Friend x As Integer Friend y As Integer

Public Sub Equivalent(ByVal Same As Point)

Page 288: Microsoft Visual Basic 2010 Tutorial

Me.x = Same.x Me.y = Same.y End Sub End Class

Public Sub ShowPoint(ByVal Coord As Point) MsgBox("Point Coordinate: P(" & Coord.x & ", " & Coord.y & ")") End Sub

Public Function Main() As Integer Dim Pt As Point = New Point

Pt.x = 4 Pt.y = 6 ShowPoint(Pt)

Dim One As Point = New Point One.Equivalent(Pt)

ShowPoint(One) Return 0 End FunctionEnd Module

This would produce:

Instead of first declaring a variable of the class and initializing it, you can create an instance of theclass in the parentheses of the calling method. To do this, you may need a constructor that canspecify the values of the fields of the class so the argument can be rightfully initialized. Here is anexample:

Public Module Exercise Public Class Point Friend x As Integer Friend y As Integer

Public Sub New()

End Sub

Public Sub New(ByVal XCoord As Integer, ByVal YCoord As Integer) Me.x = XCoord Me.y = YCoord End Sub

Public Sub Equivalent(ByVal Same As Point) Me.x = Same.x Me.y = Same.y End Sub End Class

Public Sub ShowPoint(ByVal Coord As Point) MsgBox("Point Coordinate: P(" & Coord.x & ", " & Coord.y & ")") End Sub

Public Function Main() As Integer Dim Pt As Point = New Point

Pt.x = 4 Pt.y = 6 ShowPoint(Pt)

Dim One As Point = New Point One.Equivalent(New Point(-3, 2)) ShowPoint(One)

Return 0 End FunctionEnd Module

This would produce:

Page 289: Microsoft Visual Basic 2010 Tutorial

Instead of a formal method, you can use a constructor of the class to pass an instance of thesame class. Then, in the constructor, use the argument as you see fit, knowing that all themembers of the class are available. Here is an example:

Public Class Point Friend x As Integer Friend y As Integer

Public Sub New()

End Sub

Public Sub New(ByVal XCoord As Integer, ByVal YCoord As Integer) Me.x = XCoord Me.y = YCoord End Sub

Public Sub New(ByVal Same As Point) Me.x = Same.x Me.y = Same.y End SubEnd Class

Obviously the purpose of passing a class to one of its own methods is not to find its equivalent.The C# language (actually the .NET Framework) can also take care of that (through the Equals()built-in method). Instead, you can create a method that takes an instance of the same class butmodifies that instance. For example, for our Point class, we may want to create a new point that isdistanced by one unit from the current Point object. Here is an example of doing that:

Public Module Exercise Public Class Point Friend x As Integer Friend y As Integer

Public Sub New()

End Sub

Public Sub New(ByVal XCoord As Integer, ByVal YCoord As Integer) Me.x = XCoord Me.y = YCoord End Sub

Public Sub Equivalent(ByVal Same As Point) Me.x = Same.x Me.y = Same.y End Sub

Public Sub CreatePointOneUnitAway(ByVal AddUnit As Point) Me.x = AddUnit.x + 1 Me.y = AddUnit.y + 1 End Sub End Class

Public Sub ShowPoint(ByVal Coord As Point) MsgBox("Point Coordinate: P(" & Coord.x & ", " & Coord.y & ")") End Sub

Public Function Main() As Integer Dim Pt As Point = New Point

Pt.x = 4 Pt.y = 6

Dim One As Point = New Point One.CreatePointOneUnitAway(Pt) ShowPoint(One) One.CreatePointOneUnitAway(New Point(-8, -3)) ShowPoint(One)

Return 0 End FunctionEnd Module

This would produce:

Page 290: Microsoft Visual Basic 2010 Tutorial

Returning a Class From its Own Method

You can create a method in a class that returns an instance of the class. To start, on the left sideof the method, enter the name of the class. Here is an example:

Public Class Point Public Function MethodName() As Point

End FunctionEnd Class

There are various ways you can deal with the method. If you want to return a new value of theclass, you can declare an instance of the class, initialize it, and then return it. Here is an example:

Public Module Exercise Public Class Point Friend x As Integer Friend y As Integer

Public Sub New()

End Sub

Public Sub New(ByVal XCoord As Integer, ByVal YCoord As Integer) Me.x = XCoord Me.y = YCoord End Sub

Public Sub New(ByVal Same As Point) Me.x = Same.x Me.x = Same.x End Sub

Public Function AdvanceBy5() As Point Dim Some As Point = New Point Some.x = 5 Some.y = 5 Return Some End Function End Class

Public Sub ShowPoint(ByVal Coord As Point) MsgBox("Point Coordinate: P(" & Coord.x & ", " & Coord.y & ")") End Sub

Public Function Main() As Integer Dim Pt As Point = New Point

Pt.x = 4 Pt.y = 6 ShowPoint(Pt)

Dim Away5 As Point = Pt.AdvanceBy5() ShowPoint(Away5)

Return 0 End FunctionEnd Module

This would produce:

Alternatively, you can declare an instance of the class, use the current values of the classcombined with the those of the instance to get new values, and then return the instance.

Remember that, to call a method, if it is not static, you will need to declare an instance of theclass from where you are calling the method. The second type of implementation consists ofmodifying the instance of the class that is calling the method. For example, you can add values toits fields or you can perform any other operation you want on the members of the calling instance.is an example:

Page 291: Microsoft Visual Basic 2010 Tutorial

Public Module Exercise Public Class Point Friend x As Integer Friend y As Integer

Public Sub New()

End Sub

Public Sub New(ByVal XCoord As Integer, ByVal YCoord As Integer)

Me.x = XCoord Me.y = YCoord End Sub

Public Sub New(ByVal Same As Point)

Me.x = Same.x Me.x = Same.x End Sub

REM This method adds 1 to each field of the class REM to get a new point away North-East of the current point Public Function CreatePointOneUnitAway() As Point Me.x = Me.x + 1 Me.y = Me.y + 1

Return Me End Function End Class

Public Sub ShowPoint(ByVal Coord As Point) MsgBox("Point Coordinate: P(" & Coord.x & ", " & Coord.y & ")") End Sub

Public Function Main() As Integer Dim Pt As Point = New Point

Pt.x = 4 Pt.y = 6

ShowPoint(Pt)

Dim One As Point = New Point(-8, 5) Dim Another As Point = One.CreatePointOneUnitAway() ShowPoint(Another)

Return 0 End FunctionEnd Module

This would produce:

As we have learned now, you can create a method that takes an argument that is the same typeas its parent class. In the method, you can access any member of the class, including calling theother methods of the class.

Home Copyright © 2008-2010 FunctionX

Page 292: Microsoft Visual Basic 2010 Tutorial

Nesting a Class

Description

A class can be created inside of another class. A class created inside of another is referred to asnested. To nest a class, simply create it as you would any other. Here is an example of a classcalled Inside that is nested in a class called Outside:

Public Class Outside Public Class Inside

End ClassEnd Class

In the same way, you can nest as many classes as you wish in another class and you can nest asmany classes inside of other nested classes if you judge it necessary. Just as you would manageany other class so can you exercise control on a nested class. For example, you can declare allnecessary fields, properties, or methods in the nested class or in the nesting class. When youcreate one class inside of another, there is no special programmatic relationship between bothclasses: just because a class is nested does not mean that the nested class has immediate accessto the members of the nesting class. They are two different classes and they can be usedseparately as you judge it necessary.

The name of a nested class is not "visible" outside of the nesting class. To access a nested classoutside of the nesting class, you must qualify the name of the nested class anywhere you want touse it. For example, if you want to declare an Inside variable somewhere in the program butoutside of Outside, you must qualify its name. Here is an example:

Public Module Exercise Public Class Outside Public Class Inside Public Sub New() MsgBox(" =- Inside -=") End Sub End Class

Public Sub New() MsgBox(" -= Outside =-") End Sub End Class

Public Function Main() As Integer Dim Out As Outside = New Outside

Dim Ins As Outside.Inside = New Outside.Inside

Return 0 End FunctionEnd Module

This would produce:

Because there is no programmatically privileged relationship between a nested class and its"container" class, if you want to access the nested class in the nesting class, you can use its staticmembers. In other words, if you want, you can declare static all members of the nested class thatyou want to access in the nesting class. Here is an example:

Public Module Exercise Public Class Outside Public Class Inside Public Shared InMessage As String

Public Sub New() MsgBox("=- Insider -=") InMessage = "Sitting inside while it's raining" End Sub

Page 293: Microsoft Visual Basic 2010 Tutorial

Public Shared Sub Show() msgbox("Show me the wonderful world of C# Programming") End Sub End Class

Public Sub New() MsgBox("-= Outside =-") End Sub

Public Sub Display() msgbox(Inside.InMessage) Inside.Show() End Sub End Class

Public Function Main() As Integer Dim Recto As Outside = New Outside Dim Ins As Outside.Inside = New Outside.Inside

Recto.Display()

Return 0 End FunctionEnd Module

In the same way, if you want to access the nesting class in the nested class, you can go throughthe static members of the nesting class. To do this, you can declare static all members of thenesting class that you want to access in the nested class. Here is an example:

Public Module Exercise Public Class Outside Public Class Inside Public Shared InMessage As String

Public Sub New() MsgBox("=- Insider -=") InMessage = "Sitting inside while it's raining" End Sub

Public Shared Sub Show() msgbox("Show me the wonderful world of C# Programming") End Sub

Public Sub FieldFromOutside() msgbox(Outside.OutMessage) End Sub End Class

Private Shared OutMessage As String

Public Sub New() MsgBox(" -= The Parent =-") OutMessage = "Standing outside! It's cold and raining!!" End Sub

Public Sub Display() MsgBox(Inside.InMessage) Inside.Show() End Sub End Class

Public Function Main() As Integer Dim Recto As Outside = New Outside Dim Ins As Outside.Inside = New Outside.Inside

Recto.Display()

Ins.FieldFromOutside() Return 0 End FunctionEnd Module

This would produce:

Instead of static members, if you want to access members of a nested class in the nesting class,you can first declare a variable of the nested class in the nesting class. In the same way, if youwant to access members of a nesting class in the nested class, you can first declare a variable ofthe nesting class in the nested class. Here is an example:

Page 294: Microsoft Visual Basic 2010 Tutorial

Public Module Exercise Public Class Outside REM A member of the nesting class Private OutMessage As String

REM The nested class Public Class Inside REM A field in the nested class Public InMessage As String

REM A constructor of the nested class Public Sub New() MsgBox("=- Insider -=") Me.InMessage = "Sitting inside while it's raining" End Sub

REM A method of the nested class Public Sub Show() REM Declare a variable to access the nesting class Dim Outsider As Outside = New Outside MsgBox(outsider.OutMessage) End Sub End Class REM End of the nested class

REM A constructor of the nesting class Public Sub New() Me.OutMessage = "Standing outside! It's cold and raining!!"

MsgBox("-= The Parent =-") End Sub

REM A method of the nesting class Public Sub Display() MsgBox(insider.InMessage) End Sub

REM Declare a variable to access the nested class Dim insider As Inside = New Inside End Class

Public Function Main() As Integer Dim Recto As Outside = New Outside Dim Ins As Outside.Inside = New Outside.Inside

Ins.Show() Recto.Display() Return 0 End FunctionEnd Module

This would produce:

Previous Copyright © 2008-2010 FunctionX Next

Page 295: Microsoft Visual Basic 2010 Tutorial

The Properties of a Class

Overview of Properties

Introduction

Consider the beginning of a class as follows:

File: Circle.vb

Public Class Circle Public rad As DoubleEnd Class

File: Exercise.vb

Module Exercise

Public Function Main() As Integer Dim circ As Circle = New Circle circ.rad = 25.84

Console.WriteLine(" -=- Circle Characteristics -=-") Console.WriteLine("Radius: {0}", circ.rad)

Return 0 End Function

End Module

When you create the member variables of a class or of a structure, such as the above Radius ofthe Circle class, it is a good idea not to directly expose them to other parts of the program so thatthose other parts would not be able to easily change the values of the members and retrieve theirvalues anyhow. This technique makes sure that a member variable is not accessed outside theclass (or structure) so that the clients of the class (or structure) cannot directly influence the valueof the member variable. To avoid this type of access, you can make the member variable(s)private. This would transform the above Circle class to the following:

Public Class Circle Private rad As Double

End Class

If you create a member variable as private but still want other classes (or structures) orprocedures to access or get the value of such a member variable, you should then provide ameans for members of the class to access that private member.

Accessories for Properties

A property is a member of a class that acts as an intermediary to a member variable of the class.For example, if you have a member variable of a class and that member represents the salary ofan employee, a property can be the "door" that other procedures or classes that need the salarymust present their requests to. As such, these external procedures and classes cannot just changethe salary or retrieve it as they wish. A property can be used to validate their request, to reject orto accept them.

As mentioned already, a property is used to "filter" access to a member variable of a class.Therefore, you start by declaring a (private (if you don't make it private, you may be deceiving thepurpose of creating a property)) member variable as we did for the rad member variable of theabove Circle class.

Obviously, as we learned in Lesson 21, this private member variable cannot be accessed by aprocedure or class outside of its class. Therefore, to let outside classes access this variable, youwould/can create a property. To create a property, you use the Property keyword. With regards totheir role, there are two types of properties.

Practical Learning: Introducing Properties

1. Start your programming environment

2. Create a Console Application named DeptStore3

3. To create a new class, on the main menu, click Project -> Add Class...

4. Set the Name to DepartmentStore and click Add

5. From what we know so far, type the following:

Page 296: Microsoft Visual Basic 2010 Tutorial

Public Class DepartmentStore Private pItemNo As String Private pCat As String Private pName As String Private pSize As String Private pPrice As DoubleEnd Class

6. Save the file

Types of Properties

Read-Only Properties

A property is referred to as read-only if its role is only to make available the value of the membervariable it represents. To create a read-only property, use a formula as follows (this formula takesinto consideration only the keywords we have learned so far; there are other options that wechoose to ignore at this time):

Public | Private | Protected ] [ ReadOnly ] [ Overloads | Overrides ] _[ Overridable ] | Shadows | Shared ] Property PropName As PropType Get End GetEnd Property

The optional Public, Private, or Protected keywords allow you to specify the level of access ofthe property. As introduced in the Lesson 11, the Public keyword would indicate that the propertycan be accessed outside of its class. The Private keyword would show that the property isavailable only to members of its class. The Protected keyword would indicate that the property canbe accessed by either the members of its class or only the members of classes derived from it.

The optional Shared keyword would allow you to use the property without declaring an instance ofits class.

The ReadOnly keyword is used to indicate that the property's value can be accessed but it cannotbe changed. If you are creating a read-only property, you must include the ReadOnly keyword.

The Property keyword is required. It is followed by the name of the property. The nameessentially follows the rules of Visual Basic object names. The Get keyword, the End Get and theEnd Property lines are also required.

Here is an example:

Public Class Circle ' This is a new property Public ReadOnly Property Radius() Get

End Get End PropertyEnd Class

Notice that we omitted the As keyword and the data type of the property. If you don't specify thedata type, the property is treated as Object. Otherwise, you can specify the necessary data typeof the property. Here is an example:

Public Class Circle ' This is a new property Public ReadOnly Property Radius() As Double Get

End Get End PropertyEnd Class

Between the Get and the End Get lines, you can implement the behavior that would be used tomake the member variable's value available outside. The simplest way consists of just returningthe corresponding member variable. To do this, type the Return keyword, followed by the hiddenmember variable whose value would be accessed through this property. Here is an example:

Public Class Circle

Private rad As Double

' This is a new property Public ReadOnly Property Radius() As Double Get Return rad End Get End Property

End Class

When the clients of a class access a read-only property, they can only retrieve the value of theproperty but they cannot change it. Therefore, if you create a read-only property, you should

Page 297: Microsoft Visual Basic 2010 Tutorial

provide the users with the ability to primarily specify the value of the member variable. To do this,you can create an appropriate method whose role would only be used to initialize the property.Most of the time, you would use a constructor to do this. Here is an example of such a constructorused to initialize a read-only property:

Public Class Circle

Private rad As Double

Public Sub New(ByVal r As Double) rad = r End Sub

' This is a new property Public ReadOnly Property Radius() Get Return rad End Get End Property

End Class

Once a read-only property has been created, other classes or procedures can access it, forexample they read its value as follows:

Module Exercise

Public Function Main() As Integer Dim circ As Circle = New Circle(25.84)

Console.WriteLine(" -=- Circle Characteristics -=-") Console.WriteLine("Radius: {0}", circ.Radius)

Return 0 End Function

End Module

This would produce:

-=- Circle Characteristics -=-Radius: -64.25

We described a property as serving as a door from outside to its corresponding member variable,preventing those outside classes, structures, or procedures to mess with the member variable.Notice that the Square class was given a negative value for the member variable, which is usuallyunrealistic for the side of a square. In this case and others, while still protecting the membervariable as private, you can use the read property to reset the value of the member variable oreven to reject it. To provide this functionality, you can create a conditional statement in theproperty to perform a checking process. Here is an example:

File: Circle.vb

Public Class Circle

Private rad As Double

Public Sub New() rad = 0 End Sub

Public Sub New(ByVal r As Double) rad = r End Sub

Public ReadOnly Property Radius() Get If rad < 0 Then Return 0 ' else is implied Return rad End Get End Property

End Class

File: Exercise.vb

Module Exercise

Public Function Main() As Integer Dim circ As Circle = New Circle(-64.25)

Console.WriteLine(" -=- Circle Characteristics -=-") Console.WriteLine("Radius: {0}", circ.Radius) Console.WriteLine()

circ = New Circle(38.18)

Console.WriteLine(" -=- Circle Characteristics -=-") Console.WriteLine("Radius: {0}", circ.Radius) Console.WriteLine()

Return 0 End Function

Page 298: Microsoft Visual Basic 2010 Tutorial

End Module

This would produce:

-=- Circle Characteristics -=-Radius: 0

-=- Circle Characteristics -=-Radius: 38.18

Practical Learning: Creating Property Readers

1. To create read-only properties, change the contents of the DepartmentStore file as follows: Public Class DepartmentStore Private pItemNo As String Private pCat As String Private pName As String Private pSize As String Private pPrice As Double

Public Sub New(ByVal nbr As String, ByVal ctg As String, _ ByVal nme As String, ByVal siz As String, _ ByVal prc As Double) pItemNo = nbr pCat = ctg pName = nme pSize = siz pPrice = prc End Sub

' A property for store number of a merchandise Public ReadOnly Property ItemNumber() As String Get If pItemNo = "" Then Return "Invalid Item" Else Return pItemNo End If End Get End Property

' A property for type of a merchandise Public ReadOnly Property Category() As String Get If pCat= "" Then Return "Unknown Category" Else Return pCat End If End Get End Property

' A property for the name of a merchandise Public ReadOnly Property ItemName() As String Get If pName = "" Then Return "Item no Description" Else Return pName End If End Get End Property

' A property for size of a merchandise Public ReadOnly Property Size() As String Get If pSize = "" Then Return "Unknown Size or Fits All" Else Return pSize End If End Get End Property

' A property for the marked price of an item Public ReadOnly Property UnitPrice() As Double Get If pPrice.Equals(0) Then Return 0.0 Else Return pPrice End If End Get End PropertyEnd Class

2. In the Solution Explorer, right-click Module1.vb and click Rename

3. Type it DeptStore.vb and press Enter.If asked whether you want to change the file, click Yes

4. In the Solution Explorer, double-click DeptStore.vb and change its file as follows: Module DeptStore

Page 299: Microsoft Visual Basic 2010 Tutorial

Public Function Main() As Integer Dim store As DepartmentStore = _ New DepartmentStore("53564", "Men", _ "Khaki Pants Sahara", "34", 24.95) Dim quantity As Integer = 4 Dim totalPrice As Double = store.UnitPrice * quantity

Console.WriteLine(" =#=#= Customer Invoice =#=#=") Console.WriteLine("Item #: {0}", store.ItemNumber) Console.WriteLine("Category: {0}", store.Category) Console.WriteLine("Description: {0}", store.ItemName) Console.WriteLine("Item Size: {0}", store.Size) Console.WriteLine("Unit Price: {0}", store.UnitPrice.ToString("C")) Console.WriteLine("Quantity: {0}", quantity) Console.WriteLine("Total Price: {0}" & vbCrLf, _ totalPrice.ToString("C"))

Return 0 End Function

End Module

5. Execute the program: =#=#= Customer Invoice =#=#=Item #: 53564Category: MenDescription: Khaki Pants SaharaItem Size: 34Unit Price: $24.95Quantity: 4Total Price: $99.80

6. Return to your programming environment

Write-Only Properties

In our Square class so far, we were using a constructor to initialize the value of the membervariable. This meant that we had to always make sure that we knew the value of the membervariable when we declared an instance of the class. We implemented the Radius property as read-only and the clients of the Square class could only read the value of the member variable. Insome cases, you may not want those external procedures or classes to read the value but only tobe able to change it. To provide this functionality, you can create a property that is referred to aswrite-only.

A property is called write-only if the clients of the class can change the value of that property butcannot read. The formula to create a write-only property is (once again, this formula mentionsonly the keywords we have reviewed so far):

Public | Private | Protected ] _[ WriteOnly ] [ Overloads | Overrides ] _[ Overridable ] | Shadows | Shared ] Property PropName As PropType Set(ByVal value As DataType ) End SetEnd Property

The WriteOnly keyword is used to indicate that the property's value can be changed by the clientsof the class but they cannot change it. If you are creating a write-only property, you must includethe WriteOnly keyword.

To allow clients of a class to be able to change the value of the property, the Set statement takesan argument. Here is an example:

Public Class Circle

Private rad As Double

Public Sub New() rad = 0 End Sub

Public Sub New(ByVal r As Double) rad = r End Sub

Public WriteOnly Property Radius() As Double Set(ByVal Value As Double)

End Set End Property

End Class

The minimum operation you can perform with a write-only property is to assign it a value thatwould be provided by the outside world. To do this, you can assign the value of the Set argumentto the corresponding member variable that the property represents. Here is an example:

Public Class Circle

Page 300: Microsoft Visual Basic 2010 Tutorial

Private rad As Double

Public Sub New() rad = 0 End Sub

Public Sub New(ByVal r As Double) rad = r End Sub

Public WriteOnly Property Radius() As Double Set(ByVal Value As Double) rad = Value End Set End Property

End Class

As you see, clients of a class can change the corresponding member variable of a member variablethrough the Set property writer.

Read/Write Properties

You may have realized that, if you create a read-only property without the ability to write to it,the clients of a class can only get the value of the property. On the other hand, a write-onlyproperty restricts the ability to read the value it holds. In some rare cases, you can keep thesetwo functionalities separate. In most cases, when creating a property, you would want its role toserve as a complete "door" through which the clients of a class can read or change the value of itshidden member variable. Such a property is create with read-write capabilities.

A property is referred to as read-write if it allows external classes, structures, and procedures toeither change its value or to read that value when necessary. To create a read-write property, youmust implement both the Get and the Set statements. The formula to follow would be:

Public | Private | Protected ] [ Overloads | Overrides ] _[ Overridable ] | Shadows | Shared ] Property PropName As PropType Get End Get

Set(ByVal value As DataType ) End SetEnd Property

Notice that, because this is a read-write property, you omit the ReadOnly and the WriteOnlykeywords. When implementing the property, provide the necessary functionality in the Get and Setstatements as we reviewed in the respective above sections. Here is an example:

File: Circle.vb

Public Class Circle

Private ReadOnly PI As Double = 3.14158 Private rad As Double

Public Sub New() rad = 0 End Sub

Public Sub New(ByVal r As Double) rad = r End Sub

Public Property Radius() As Double Get If rad < 0 Then Return 0 Else Return rad End If End Get

Set(ByVal Value As Double) rad = Value End Set End Property

Public ReadOnly Property Diameter() As Double Get Return rad * 2 End Get End Property

Public ReadOnly Property Circumference() As Double Get Return Diameter * PI End Get End Property

Public ReadOnly Property Area() As Double Get Return rad * rad * PI

Page 301: Microsoft Visual Basic 2010 Tutorial

End Get End Property

End Class

File: Exercise.vb

Module Exercise

Public Function Main() As Integer Dim circ As Circle = New Circle(64.25)

Console.WriteLine(" -=- Circle Characteristics -=-") Console.WriteLine("Radius: {0}", circ.Radius) Console.WriteLine("Diameter: {0}", circ.Diameter) Console.WriteLine("Circumference: {0}", circ.Circumference) Console.WriteLine("Area: {0}" & vbCrLf, circ.Area)

Return 0 End Function

End Module

This would produce:

-=- Circle Characteristics -=-Radius: 64.25Diameter: 128.5Circumference: 403.69303Area: 12968.63858875

Practical Learning: Creating Read/Write Properties

1. Access the DepartmentStore file

2. To create read-write properties and complete the program, change the content of the file asfollows: Public Class DepartmentStore Private pItemNo As String Private pCat As String Private pName As String Private pSize As String Private pPrice As Double

Public Sub New(ByVal nbr As String, ByVal ctg As String, _ ByVal nme As String, ByVal siz As String, _ ByVal prc As Double) pItemNo = nbr pCat = ctg pName = nme pSize = siz pPrice = prc End Sub

' A property for store number of a merchandise Public Property ItemNumber() As String Get If pItemNo = "" Then Return "Invalid Item" Else Return pItemNo End If End Get

Set(ByVal Value As String) pItemNo = Value End Set End Property

' A property for type of a merchandise Public Property Category() As String Get If pCat = "" Then Return "Unknown Category" Else Return pCat End If End Get

Set(ByVal Value As String) pCat = Value End Set End Property

' A property for the name of a merchandise Public Property ItemName() As String Get If pName = "" Then Return "Item no Description" Else Return pName End If End Get

Set(ByVal Value As String) pName = Value

Page 302: Microsoft Visual Basic 2010 Tutorial

End Set End Property

' A property for size of a merchandise Public Property Size() As String Get If pSize = "" Then Return "Unknown Size or Fits All" Else Return pSize End If End Get

Set(ByVal Value As String) pSize = Value End Set End Property

' A property for the marked price of an item Public Property UnitPrice() As Double Get If pPrice = 0 Then Return 0.0 Else Return pPrice End If End Get

Set(ByVal Value As Double) pPrice = Value End Set End PropertyEnd Class

3. Access the DeptStore.vb file and change it as follows: Module DeptStore

Public Function Main() As Integer Dim item1 As DepartmentStore = _ New DepartmentStore("53564", "Men", _ "Khaki Pants Sahara", "34", 24.95) Dim quantity As Integer = 4 Dim totalPrice As Double

With item1 totalPrice = .UnitPrice * quantity

Console.WriteLine(" =#=#= Customer Invoice =#=#=") Console.WriteLine("Item #: {0}", .ItemNumber) Console.WriteLine("Category: {0}", .Category) Console.WriteLine("Description: {0}", .ItemName) Console.WriteLine("Item Size: {0}", .Size) Console.WriteLine("Unit Price: {0}", .UnitPrice.ToString("C")) Console.WriteLine("Quantity: {0}", quantity) Console.WriteLine("Total Price: {0}" & vbCrLf, _ totalPrice.ToString("C"))

.ItemNumber = "74797" .Category = "Womn" .ItemName = "Suit Gallantry" .Size = "10-1/4" .UnitPrice = 225.75 quantity = 2

Console.WriteLine(" =#=#= Customer Invoice =#=#=") Console.WriteLine("Item #: {0}", .ItemNumber) Console.WriteLine("Category: {0}", .Category) Console.WriteLine("Description: {0}", .ItemName) Console.WriteLine("Item Size: {0}", .Size) Console.WriteLine("Unit Price: {0}", .UnitPrice.ToString("C")) Console.WriteLine("Quantity: {0}", quantity) Console.WriteLine("Total Price: {0}" & vbCrLf, _ totalPrice.ToString("C")) End With

Return 0 End Function

End Module

4. Execute the program: =#=#= Customer Invoice =#=#=Item #: 53564Category: MenDescription: Khaki Pants SaharaItem Size: 34Unit Price: $24.95Quantity: 4Total Price: $99.80

=#=#= Customer Invoice =#=#=Item #: 74797Category: WomnDescription: Suit GallantryItem Size: 10-1/4Unit Price: $225.75Quantity: 2Total Price: $99.80

Page 303: Microsoft Visual Basic 2010 Tutorial

5. Close the DOS window and return to your programming environment

Built-In Properties

Introduction

To assist you with your various programming tasks, the Visual Basic language provides many built-in classes that are equipped with many properties.

To find out the date of the system clock of the computer on which your application is running, youcan access a property named Today. This property is of type Date:

Public Property Today() As DateTime

This is an example of using it;

Public Module Exercise

Public Function Main() As Integer MsgBox("Today is " & Today)

Return 0 End Function

End Module

Previous Copyright © 2009-2010 FunctionX, Inc. Next

Page 304: Microsoft Visual Basic 2010 Tutorial

Operator Overloading

Fundamentals of Overloading an Operator

Introduction

In elementary school, we learned how to perform arithmetic operations such as adding 2 to 5 toget 7. We also learned somehow how to add letters to create a word, how to add words to createa sentence, and how to add symbols to create abbreviations. In programming, we learn how tocreate classes that are made of more than one value. When necessary, we may want to add thevalues of those classes to get new values. Unfortunately, those classes are not equipped toperform arithmetic operations or comparisons on their objects. Fortunately, if you judge itnecessary, you can write code that makes it possible.

We know many of the operators available in the Visual Basic language. We also reviewed some ofthe ways they can be used. We saw that there are rules that must be followed when using any ofthose operators.

Operator overloading consists of customizing the behavior of a Visual Basic operator to be able toapply it on the values of a class. This means that you must create a special behavior in your classfor a particular operator you want to use.

A class whose operators you want to overload primarily starts like any class. You can add anymembers you judge necessary to it. Make sure you provide appropriate and realistic constructorsso the class can be initialized appropriately. The other important detail you should take care of ishow the value of the class will be accessed outside. Probably the easiest way to do this consists ofoverriding the ToString() method in it.

Here is an example of a class:

Public Class Natural Public Number As Integer

Public Sub New(ByVal N As Integer) Number = N End Sub

Public Overrides Function ToString() As String Return Number.ToString() End FunctionEnd Class

Application: Introducing Operator Overloading

1. Start Microsoft Visual Basic

2. To start a new application, on the Start Page, click File -> New Project...

3. In the middle list, click Class Library

4. Change the Name to Mathematics

5. Click OK

6. In the Solution Explorer, right-click Class1.vb and click Rename

7. Type Arithmetic.vb and press Enter

8. To save the project, on the Standard toolbar, click the Save All button

9. Make a note of the location and click Save

10. Change the file as follows:

Public Class Arithmetic Public Shared Function GreatestCommonDivisor(ByVal a As Long, ByVal b As Long) Dim Remainder As Long

While b <> 0 Remainder = a Mod b a = b b = Remainder End While

Return a End FunctionEnd Class

Page 305: Microsoft Visual Basic 2010 Tutorial

11. To create the library, in the Solution Explorer, right-click Mathematics and click Build

12. To create a new project, on the main menu, click File -> New Project...

13. In the middle list, click Console Application

14. Change the name to Algebra1

15. Click OK

16. On the main menu, click Project -> Algebra1 Properties

17. Click the arrow of the Application Type box and select Windows Forms Application

18. In the Solution Explorer, right-click Module1.vb and click Rename

19. Type Algebra.vb and press Enter twice

20. Change the document as follows:

Module Algebra

Public Function Main() As Integer

Return 0 End Function

End Module

21. In the Solution Explorer, right-click Algebra1 and click Add Reference...

22. Click the Browse tab

23. Locate the folder where the Mathematics library was created

24. Select Mathematics.dll

25. Click OK

26. To create a new class, in the Class View, right-click Algebra1 -> Add -> Class...

27. Set the Name to Rational

28. Click Add

29. Change the file as follows:

Imports Mathematics

Public Class Rational Private Num As Long Private Den As Long

Public Sub New(ByVal n As Long, ByVal d As Long) Num = n Den = d End Sub

Public Property Numerator() As String Get Return Num / Arithmetic.GreatestCommonDivisor(Num, Den) End Get Set(ByVal value As String) Num = value End Set End Property

Public Property Denominator() As String Get Return Den / Arithmetic.GreatestCommonDivisor(Num, Den) End Get Set(ByVal value As String) Den = value End Set End Property

Public Overrides Function ToString() As String Dim Numer As Long Dim Denom As Long

Numer = Num / Arithmetic.GreatestCommonDivisor(Num, Den) Denom = Den / Arithmetic.GreatestCommonDivisor(Num, Den)

If Denom = 1 Then Return Numer.ToString() Else Return String.Format("{0}/{1}", Numer, Denom) End If End FunctionEnd Class

The Formula

To overload an operator, you must create a Shared method using the following formula:

[ <attrlist> ] Public [ Overloads ] Shared [ Shadows ] [ Widening | Narrowing ] Operator operatorsymbol ( operand1 [, operand2 ]) [ As [ <attrlist> ] type ] [ statements ] [ statements ]

Page 306: Microsoft Visual Basic 2010 Tutorial

Return returnvalue [ statements ]End Operator

You can start with the Public access modifier, followed by the Shared keyword. You can useadditional keywords and/or mechanisms to control access to the method. You must then use theOperator keyword. This is followed by the actual operator you want to customize. There are rulesyou must, and suggestions you should, follow:

Not all operators need to be customized for all classes. For example, while it would be feasibleto add two books to get a new book that includes all the pages on both books and theircombined authors, it may not be realistic to multiply two books (to get what?). Therefore, youshould select the right operator based on your needs

While some operators are always available to be overloaded, some operators have restrictiverules. This means that you cannot just use any operator anyhow

Not all operators are overloadable

After the operator, open that parentheses that must always be used on a function. In theparentheses, you will add one or more arguments, depending on the operator. After the closingparenthesis, you must specify a return type. Normally, you should return the class itself. After all,the operator will act on an object of its class type. For this reason, the method should return avalue that represents its class.

To end the method, you must use the End Operator expression. In the body of the method, youcan implement the behavior and make sure you return a value. After defining the method, you cancall it either inside or outside the class.

Overloading an Operator

Unary Operators

A unary operator is one that acts on one value. The Visual Basic language provides many unaryoperators but not all can be overloaded. The unary operarors available for overloading are +, -,Not, IsTrue, IsFalse, and CType.

To overload a unary operator, pass one argument to the parentheses of the method. In the bodyof the method, perform the desired operation. Here is an example of overloading a unaryoperator:

Public Class Natural Public Number As Integer

Public Sub New(ByVal N As Integer) Number = N End Sub

Public Shared Operator Not(ByVal Value As Natural) As Natural

Dim Nbr As Integer = Value.Number Dim N As Integer = Not Nbr

Dim Nat As Natural = New Natural(N)

Return Nat End Operator

Public Overrides Function ToString() As String Return Number.ToString() End FunctionEnd Class

Here is an example of applying that operator:

Public Module Exercise

Public Function Main() As Integer Dim Nbr As Natural

Nbr = New Natural(1405)

MsgBox("The bitwise nagation of " & Nbr.ToString() & " is " & (Not Nbr).ToString())

Return 0 End Function

End Module

This would produce:

Page 307: Microsoft Visual Basic 2010 Tutorial

In the same way, you can overload the other operators.

Binary Arithmetic Operators

A binary operator is one that acts on two values. The values must be of the same type. The VisualBasic language provides a rich set of binary operators. Those used in arithmetics are: +, -, *, /, \,and Mod.

To overloaded a binary arithmetic operator, pass two arguments to the parentheses of the method.The first arguments must be of the type of class in which you are working. The second argumentcan be another type. Here is an example:

Public Class Natural Public Number As Integer

Public Sub New(ByVal N As Integer) Number = N End Sub

Public Shared Operator Not(ByVal Value As Natural) As Natural

Dim Nbr As Integer = Value.Number Dim N As Integer = Not Nbr

Dim Nat As Natural = New Natural(N)

Return Nat End Operator

Public Shared Operator +(ByVal Value As Natural, ByVal Add As Integer) As Natural Dim Nbr As Integer = Value.Number Dim N As Integer = Nbr + Add

Dim Nat As Natural = New Natural(N) Return Nat End Operator

Public Overrides Function ToString() As String Return Number.ToString() End FunctionEnd Class

Here is an example of using the operator:

Public Module Exercise

Public Function Main() As Integer Dim Nbr As Natural

Nbr = New Natural(248)

MsgBox(Nbr.ToString() & " + 35 = " & (Nbr + 35).ToString())

Return 0 End Function

End Module

This would produce:

If you want to perform the operations on two similar types of values, then the second argumentmust be of the same type as the first, which is the class you are using.

Application: Overloading Binary Operators

Page 308: Microsoft Visual Basic 2010 Tutorial

1. Access the Rational.vb file and change it as follows:

2. Access the Algebra.vb file and change it as follows:

Imports Mathematics

Public Class Rational Private Num As Long Private Den As Long

Public Sub New(ByVal n As Long, ByVal d As Long) Num = n Den = d End Sub

Public Property Numerator() As String Get Return Num / Arithmetic.GreatestCommonDivisor(Num, Den) End Get Set(ByVal value As String) Num = value End Set End Property

Public Property Denominator() As String Get Return Den / Arithmetic.GreatestCommonDivisor(Num, Den) End Get Set(ByVal value As String) Den = value End Set End Property

Public Shared Operator +(ByVal First As Rational, ByVal Second As Rational) As Rational Dim Top As Long Dim Bottom As Long

Top = (First.Numerator * Second.Denominator) + (First.Denominator * Second.Numerator) Bottom = First.Denominator * Second.Denominator

Return New Rational(Top, Bottom) End Operator

Public Shared Operator -(ByVal First As Rational, ByVal Second As Rational) As Rational Dim Top As Long Dim Bottom As Long

Top = (First.Numerator * Second.Denominator) - (First.Denominator * Second.Numerator) Bottom = First.Denominator * Second.Denominator

Return New Rational(Top, Bottom) End Operator

Public Shared Operator *(ByVal First As Rational, ByVal Second As Rational) As Rational Dim Top As Long Dim Bottom As Long

Top = First.Numerator * Second.Numerator Bottom = First.Denominator * Second.Denominator

Return New Rational(Top, Bottom) End Operator

Public Shared Operator /(ByVal First As Rational, ByVal Second As Rational) As Rational Dim Top As Long Dim Bottom As Long

Top = First.Numerator * Second.Denominator Bottom = First.Denominator * Second.Numerator

Return New Rational(Top, Bottom) End Operator

Public Overrides Function ToString() As String Dim Numer As Long Dim Denom As Long

Numer = Num / Arithmetic.GreatestCommonDivisor(Num, Den) Denom = Den / Arithmetic.GreatestCommonDivisor(Num, Den)

If Denom = 1 Then Return Numer.ToString() Else Return String.Format("{0}/{1}", Numer, Denom) End If End FunctionEnd Class

Module Algebra

Public Function Main() As Integer Dim a, b, c, d As Long Dim FirstFraction As Rational = Nothing Dim SecondFraction As Rational = Nothing

Page 309: Microsoft Visual Basic 2010 Tutorial

3. To execute the application, on the main menu, click Debug -> Start Debugging

4. Click OK

5. When requested, enter the first numerator as 128 and press Enter

6. Enter the first denominator as 54 and press Enter

7. Enter the second numerator as 88 and press Enter

8. Enter the second denominator as 36 and press Enter

MsgBox("This program allows you to perform " & "an arithmetic operation on two fractions") a = CLng(InputBox("=-= First Fraction =-=" & vbCrLf & "Enter the numerator:")) b = CLng(InputBox("=-= First Fraction =-=" & vbCrLf & "Enter the denominator: ")) c = CLng(InputBox("=-= Second Fraction =-=" & vbCrLf & "Enter the numerator:")) d = CLng(InputBox("=-= Second Fraction =-=" & vbCrLf & "Enter the denominator:"))

FirstFraction = New Rational(a, b) MsgBox(String.Format("First Fraction: {0}/{1} => {2}", a, b, FirstFraction)) SecondFraction = New Rational(c, d) MsgBox(String.Format("Second Fraction: {0}/{1} => {2}", c, d, SecondFraction))

Dim Addition As Rational Dim Subtraction As Rational Dim Multiplication As Rational Dim Division As Rational

Addition = FirstFraction + SecondFraction MsgBox(String.Format("Addition: {0}/{1} + {2}/{3} = {4}", a, b, c, d, Addition))

Subtraction = FirstFraction - SecondFraction MsgBox(String.Format("Addition: {0}/{1} + {2}/{3} = {4}", a, b, c, d, Subtraction))

Multiplication = FirstFraction * SecondFraction MsgBox(String.Format("Addition: {0}/{1} + {2}/{3} = {4}", a, b, c, d, Multiplication))

Division = FirstFraction / SecondFraction MsgBox(String.Format("Addition: {0}/{1} + {2}/{3} = {4}", a, b, c, d, Division))

Return 0 End Function

End Module

Page 310: Microsoft Visual Basic 2010 Tutorial

Binary Bitwise Operators

Besides the traditional arithmetic operations, Visual Basic support the ability to add or shift bits inthe computer memory. These operators are the bitwise conjunction operator & and its assignmentoperator &=, the bitwise disjunction operator | and its assignment operator |=, the bitwiseexclusion operator ^ and its assignment operator ^=, the left-shift operator << and its assigmentoperator <<=, the right-shift operator >> and its assignment operator >>=. When necessary,overload only the primary operator (&, |, ^, <<, >>) and its equivalent assignment operator willbe automatically provided by the compiler.

To overloaded a binary operator, pass two arguments to the parentheses of the method. For thetwo bitwise shift operators, << and >>, the first argument must be the class in which you areworking and the second argument must by a constant integer (type int). Here is an example thatoverloads the left bitwise shifter <<:

Public Class Natural Public Number As Integer

Public Sub New(ByVal N As Integer) Number = N End Sub

Public Shared Operator Not(ByVal Value As Natural) As Natural

Dim Nbr As Integer = Value.Number Dim N As Integer = Not Nbr

Dim Nat As Natural = New Natural(N)

Return Nat End Operator

Public Shared Operator +(ByVal Value As Natural, ByVal Add As Integer) As Natural Dim Nbr As Integer = Value.Number Dim N As Integer = Nbr + Add

Dim Nat As Natural = New Natural(N) Return Nat End Operator

Public Shared Operator <<(ByVal Value As Natural, ByVal Shifts As Integer) As Natural Dim Nbr As Integer = Value.Number

Page 311: Microsoft Visual Basic 2010 Tutorial

Dim N As Integer = (Nbr << Shifts)

Dim Nat As Natural = New Natural(N) Return Nat End Operator

Public Overrides Function ToString() As String Return Number.ToString() End FunctionEnd Class

Here is an example of using the operator:

Public Module Exercise

Public Function Main() As Integer Dim Nbr As Natural

Nbr = New Natural(1248)

MsgBox("Shiftting the bits of " & Nbr.ToString() & " to the left by 4 is " & (Nbr << 4).ToString())

Return 0 End Function

End Module

This would produce:

For the operators that join or disjoin two series of bits:

The first argument must be the class on which you are working. The second argument can bean integer. Here is an example:

Public Shared Operator And(ByVal Value As Natural, ByVal Constant As Integer) As Natural Dim Result As Integer = Value.Number And Constant

Return New Natural(Result)End Operator

-----------------------------------------------------------------------

Public Module Exercise

Public Function Main() As Integer Dim Nbr As Natural

Nbr = New Natural(286)

MsgBox("286 AND 4075 = " & (Nbr And 4075).ToString())

Return 0 End Function

End Module

The first argument must be the class on which you are working. The second argument can bea class of the same type as the first argument. Here is an example:

Public Class Natural Public Number As Integer

Public Sub New(ByVal N As Integer) Number = N End Sub

Public Shared Operator Not(ByVal Value As Natural) As Natural

Dim Nbr As Integer = Value.Number

Page 312: Microsoft Visual Basic 2010 Tutorial

Dim N As Integer = Not Nbr

Dim Nat As Natural = New Natural(N)

Return Nat End Operator

Public Shared Operator +(ByVal Value As Natural, ByVal Add As Integer) As Natural Dim Nbr As Integer = Value.Number Dim N As Integer = Nbr + Add

Dim Nat As Natural = New Natural(N) Return Nat End Operator

Public Shared Operator <<(ByVal Value As Natural, ByVal Shifts As Integer) As Natural Dim Nbr As Integer = Value.Number Dim N As Integer = (Nbr << Shifts)

Dim Nat As Natural = New Natural(N) Return Nat End Operator

Public Shared Operator And(ByVal Value As Natural, ByVal Constant As Integer) As Natural Dim Result As Integer = Value.Number And Constant

Return New Natural(Result) End Operator

Public Shared Operator And(ByVal Operand1 As Natural, ByVal Operand2 As Natural) As Natural Dim Result As Integer = Operand1.Number And Operand2.Number

Return New Natural(Result) End Operator

Public Overrides Function ToString() As String Return Number.ToString() End FunctionEnd Class

---------------------------------------------------

Public Module Exercise

Public Function Main() As Integer Dim Nbr1 As Natural = New Natural(52) Dim Nbr2 As Natural = New Natural(2447)

MsgBox("52 AND 2447 = " & (Nbr1 And Nbr2).ToString())

Return 0 End Function

End Module

This would produce:

In the same way you can overload the other operators.

Comparison Operators

As its name implies, a comparison is used to find out whether one of two values is higher than theother. The values must be of the same type. Comparison operators go in pair. That is, if you wantto compare two values for equality, you must also be able to know when they are different. Forthis reason, if you decide to overload a comparison operator, you must also overload its opposite:

If you overload =, you must also overload <> and vice versa

If you overload <, you must also overload > and vice versa

If you overload <=, you must also overload >= and vice versa

If you overload IsTrue, you must also overload IsFalse and vice versa

We know that the Object class is equipped with a method named Equals. That method makes itpossible to find out whether one object is equal to another. And since all classes in a Visual Basicapplication derive from Object, if you decide to overload a couple of comparison operators, youshould also override the Equals() method.

Page 313: Microsoft Visual Basic 2010 Tutorial

Restricted Operators

Some operators either cannot be overloaded or depend on other operators being overloaded. Thefollowing operators cannot be overloaded: =, AddressOf, AndAlso, AsType, GetType, Is,IsNot, New, OrElse, and TypeOf ... Is.

Application: Ending the Lesson

1. Close your programming environment

2. When asked whether you want to save, click No

Home Copyright © 2010 FunctionX, Inc.

Page 314: Microsoft Visual Basic 2010 Tutorial

Inheritance

Introduction to Inheritance

Definition

Imagine you create a class used to process calculations for a circle. The class may appear asfollows:

Module Exercise Public Class Circle Public Radius As Double

Public Function CalculateDiameter() As Double Return Radius * 2 End Function

Public Function CalculateCircmuference() As Double Return CalculateDiameter() * 3.14159 End Function

Public Function CalculateArea() As Double Return Radius * Radius * 3.14159 End Function End Class

Public Function Main() As Integer Dim circ As Circle = New Circle circ.Radius = 25.84

Console.WriteLine(" -=- Circle Characteristics -=-") Console.WriteLine("Radius: {0} ", circ.Radius) Console.WriteLine("Diameter: {0} ", circ.CalculateDiameter()) Console.WriteLine("Circmuference: {0} ", circ.CalculateCircmuference()) Console.WriteLine("Area: {0} " & vbCrLf, circ.CalculateArea())

Return 0 End Function

End Module

This would produce:

-=- Circle Characteristics -=-Radius: 25.55Diameter: 51.1Circmuference: 160.535249Area: 2050.837805975

After creating this class, imagine you want to create another class used to process a sphere. Youmay start thinking of creating a new class and redefining the members similar to those that belongto the above Circle class. To make this easier, you may just select the code of the Circle class,copy it, and then paste it in your document. Fortunately, when a class hold a foundation thatanother class can use, you can create the new class that is based on the old one: this is thefoundation of class inheritance, or simply called inheritance.

Inheritance is the process of creating a new class that is based on an existing class.

Class Derivation

As you may have guessed, in order to implement inheritance, you must first have a class thatprovides the fundamental definition or behavior you need. There is nothing magical about such aclass. It could appear exactly like any of the classes we have used so far.

The above Circle class is used to process a circle. It can request or provide a radius. It can alsocalculate the circumference and the area of a circle. Since a sphere is primarily a 3-dimensionalcircle, and if you have a class for a circle already, you can simply create your sphere class thatuses the already implemented behavior of a circle class.

Creating a class that is based on another class is also referred to as deriving a class from another.The first class serves as parent or base. The class that is based on another class is also referred toas child or derived. To create a class based on another, you use the following formula:

Class Child Inherits Parent

' Body of the new class

End Class

In this formula, you start with the Class keyword, followed by a name for your new class, followed

Page 315: Microsoft Visual Basic 2010 Tutorial

by an end of line. On the next line, type the Inherits keyword, followed by the name of the classon which the new Child class would be based. Of course, the Parent class must have been defined;that is, the compiler must be able to find its definition. Based on the above formula, you cancreate a sphere class based on the earlier mentioned Circle class as follows:

Public Class Circle

End Class

Class Sphere Inherits Circle

End Class

If you want to be able to access the class from other languages, you can precede its name withthe Public keyword:

Public Class Circle

End Class

Public Class Sphere Inherits Circle

End Class

Otherwise, if you intend to use it only in the current project, you can precede the Class of theclass' name with the Private keyword.

Characteristics of Inheritance

Private Members

After deriving a class, it becomes available and you can use it just as you would any other class.Here is an example:

Module Exercise

Public Function Main() As Integer Dim ball As Sphere = New Sphere

Return 0 End Function

End Module

When a class is based on another class, all public members of the parent class are made availableto the derived class that can use them as necessary. While other methods and classes can also usethe public members of a class, the difference is that the derived class can call the public membersof the parent as if they belonged to the derived class. That is, the child class doesn't have to"qualify" the public members of the parent class when these public members are used in the bodyof the derived class. This is illustrated in the following program:

Code File: Circle.vb

Public Class Circle Public Radius As Double

Public Function CalculateDiameter() As Double Return Radius * 2 End Function

Public Function CalculateCircumference() As Double Return CalculateDiameter() * 3.14159 End FunctionEnd Class

Public Class Sphere Inherits Circle

Public Sub ShowCharacteristics() ' Because Sphere is based on Circle, you can access ' any public member(s) of Circle without qualifying it(them) Radius = 35.84

Console.WriteLine("Circle Characteristics") Console.WriteLine("=======================================================") Console.WriteLine("Radius: {0}", Radius) Console.WriteLine("Diameter: {0}", CalculateDiameter()) Console.WriteLine("Circumference: {0}", CalculateCircumference()) Console.WriteLine("=======================================================") End SubEnd Class

Code File: Exercise.vb

Module Exercise

Page 316: Microsoft Visual Basic 2010 Tutorial

Public Function Main() As Integer Dim ball As Sphere = New Sphere

ball.ShowCharacteristics()

Return 0 End Function

End Module

This would produce:

Sphere CharacteristicsRadius: 35.84Diameter: 71.68Circumference: 225.1891712

Based on the relationship between a child class and its parent, you can use Me in the child toaccess the public members of the parent class. Here is an example:

Public Class Circle Public Radius As Double

Public Function CalculateDiameter() As Double Return Radius * 2 End Function

Public Function CalculateCircumference() As Double Return CalculateDiameter() * 3.14159 End FunctionEnd Class

Public Class Sphere Inherits Circle

Public Sub ShowCharacteristics() ' Because Sphere is based on Circle, you can access ' any public member(s) of Circle without qualifying it(them) Me.Radius = 35.84

Console.WriteLine("Circle Characteristics") Console.WriteLine("=======================================================") Console.WriteLine("Radius: {0}", Me.Radius) Console.WriteLine("Diameter: {0}", Me.CalculateDiameter()) Console.WriteLine("Circumference: {0}", Me.CalculateCircumference()) Console.WriteLine("=======================================================") End SubEnd Class

We mentioned that, when deriving a new class based on an existing one, all public members of theparent class are accessible to its child classes. In fact, those public members are also available toall other non-child classes and external procedures of the parent class. On the other hand, whencreating a class, if you think that a certain member would not need to be accessed outside of theclass, you should make it private by starting it with the Private keyword. Here is an example:

Public Class Circle Public Radius As Double

Private Function ShowDescription() Return "A circle is a round geometric shape constructed " & _ "so that all considered points of the shape are " & _ "at an equal distance from a common point called " & _ "the center. Also, two equally opposite points from " & _ "the center are at the exact same dictance from that center." End Function

Public Function CalculateDiameter() As Double Return Radius * 2 End Function

Public Function CalculateCircumference() As Double Return CalculateDiameter() * 3.14159 End FunctionEnd Class

After creating a class, its private members are not accessible to clients of the class, not even tothe children of that class. If you attempt to access a private member of a class outside of thatclass, you would receive an error. That what would happen with the following program:

Public Class Circle Public Radius As Double

Private Function ShowDescription() Return "A circle is a round geometric shape constructed " & _ "so that all considered points of the shape are " & _ "at an equal distance from a common point called " & _ "the center. Also, two equally opposite points from " & _ "the center are at the exact same dictance from that center." End Function

Public Function CalculateDiameter() As Double Return Radius * 2 End Function

Public Function CalculateCircumference() As Double Return CalculateDiameter() * 3.14159 End Function

Page 317: Microsoft Visual Basic 2010 Tutorial

End Class

Public Class Sphere Inherits Circle

Public Sub ShowCharacteristics() ' Because Sphere is based on Circle, you can access ' any public member(s) of Circle without qualifying it(them) Me.Radius = 35.84

Console.WriteLine("Circle Characteristics") Console.WriteLine("=======================================================") Console.WriteLine("Description: {0}", ShowDescription()) Console.WriteLine("Radius: {0}", Me.Radius) Console.WriteLine("Diameter: {0}", Me.CalculateDiameter()) Console.WriteLine("Circumference: {0}", Me.CalculateCircumference()) Console.WriteLine("=======================================================") End SubEnd Class

Protected Members

When creating a class that would be used as the base of other classes, in some cases, you maywant to create a special relationship among a class and its eventual children. For example, youmay want to create some members of the parent class that only its derived class can access.These types of members must be created with the Protected keyword. Here is an example:

Public Class Circle Protected Radius As Double

Private Function ShowDescription() Return "A circle is a round geometric shape constructed " & _ "so that all considered points of the shape are " & _ "at an equal distance from a common point called " & _ "the center. Also, two equally opposite points from " & _ "the center are at the exact same dictance from that center." End Function

Public Function CalculateDiameter() As Double Return Radius * 2 End Function

Public Function CalculateCircumference() As Double Return CalculateDiameter() * 3.14159 End FunctionEnd Class

Not just the member variables but you can also create methods as protected as long as you intendit only for the class and its children. Remember that a protected member cannot be accessed bythe clients of the class, only by the class itself and its children.

When accessing the protected members of a class from its children, you can use Me to locatethose members: Me gives you access to non-Shared public and protected members of both theparent(s) and its class. Here is an example:

Public Class Circle Protected Radius As Double

Protected Function ShowDescription() Return "A circle is a round geometric shape constructed " & _ "so that all considered points of the shape are " & _ "at an equal distance from a common point called " & _ "the center. Also, two equally opposite points from " & _ "the center are at the exact same dictance from that center." End Function

Public Function CalculateDiameter() As Double Return Radius * 2 End Function

Public Function CalculateCircumference() As Double Return CalculateDiameter() * 3.14159 End FunctionEnd Class

Public Class Sphere Inherits Circle

Public Sub ShowCharacteristics() ' Because Sphere is based on Circle, you can access ' any public member(s) of Circle without qualifying it(them) Me.Radius = 35.84

Console.WriteLine("Circle Characteristics") Console.WriteLine("=======================================================") Console.WriteLine("Description: {0}", Me.ShowDescription()) Console.WriteLine("-=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=-") Console.WriteLine("Radius: {0}", Me.Radius) Console.WriteLine("Diameter: {0}", Me.CalculateDiameter()) Console.WriteLine("Circumference: {0}", Me.CalculateCircumference()) Console.WriteLine("=======================================================") End SubEnd Class

Page 318: Microsoft Visual Basic 2010 Tutorial

Previous Copyright © 2009-2010 FunctionX, Inc. Next

Page 319: Microsoft Visual Basic 2010 Tutorial

Polymorphism

Polymorphism Fundamentals

Introduction

As mentioned already, inheritance allows you to reuse, in a child class, code that is alreadyimplemented in a parent class. In some cases, that original code will be enough. In some othercases, you will need to apply new behavior to a child class even though the parent class alreadyhas a behavior close to what you seek.

Re-creating a method in a child class using the same signature (name and arguments, if any) of amethod of a parent class is referred to as overriding. Based on this, if a derived and a parentclasses have the same member but implemented differently, when accessing that in your code,you need to know what particular member you are referring to, the parent or the derived's. This isthe basis of polymorphism.

Overriding a Method

When creating the above two classes, imagine that you want to create a method that displays thecharacteristics of each shape. The method would belong to its corresponding class. This can bedone as follows:

File: Circle.vb

Public Class Circle

Protected Radius As Double

Protected Function ShowDescription() Return "A circle is a round geometric shape " & vbCrLf & _ "constructed so that all considered points of the " & vbCrLf & _ "shape are at an equal distance from a common point " & vbCrLf & _ "called the center. Also, two equally opposite points " & vbCrLf & _ "from the center are at the exact same dictance from " & vbCrLf & _ "that center." End Function

Public Function CalculateDiameter() As Double Return Radius * 2 End Function

Public Function CalculateCircumference() As Double Return CalculateDiameter() * 3.14159 End Function

Public Sub ShowCharacteristics() Console.WriteLine("Circle Characteristics") Console.WriteLine("=======================================================") Console.WriteLine("Description: {0}", Me.ShowDescription()) Console.WriteLine("-=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=-") Console.WriteLine("Radius: {0}", Radius) Console.WriteLine("Diameter: {0}", CalculateDiameter()) Console.WriteLine("Circumference: {0}" & vbCrLf, CalculateCircumference()) End Sub

End Class

Public Class Sphere Inherits Circle

Public Sub ShowCharacteristics() ' Because Sphere is based on Circle, you can access ' any public member(s) of Circle without qualifying it(them)

Console.WriteLine("Sphere Characteristics") Console.WriteLine("=======================================================") Console.WriteLine("Description: {0}", Me.ShowDescription()) Console.WriteLine("-=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=-") Console.WriteLine("Radius: {0}", Me.Radius) Console.WriteLine("Diameter: {0}", Me.CalculateDiameter()) Console.WriteLine("Circumference: {0}", Me.CalculateCircumference()) Console.WriteLine("=======================================================") End Sub

End Class

When creating a class such as the above Circle, if you create a member that the class' childrenwould override, you can (should/must) indicate this to the compiler. This is done by preceding itwith the Overridable keyword. This would be done as follows:

Public Class Circle Public Ovirridable Sub ShowCharacteristics()

Page 320: Microsoft Visual Basic 2010 Tutorial

End SubEnd Class

Private Class Sphere Inherits Circle

Public Sub ShowCharacteristics() End SubEnd Class

Once the member has been marked as overridable, when implementing the child class, in order tooverride it, you must mark the corresponding member of the child class as override. To do this,precede it with the Overrides keyword. This would be done as follows:

File: Circle.vb

Public Class Circle

Protected Radius As Double

Protected Overridable Function ShowDescription() Return "A circle is a round geometric shape " & vbCrLf & _ "constructed so that all considered points of the " & vbCrLf & _ "shape are at an equal distance from a common point " & vbCrLf & _ "called the center. Also, two equally opposite points " & vbCrLf & _ "from the center are at the exact same dictance from " & vbCrLf & _ "that center." End Function

Public Function CalculateDiameter() As Double Return Radius * 2 End Function

Public Function CalculateCircumference() As Double Return CalculateDiameter() * 3.14159 End Function

Public Overridable Sub ShowCharacteristics() Me.Radius = 35.84

Console.WriteLine("Circle Characteristics") Console.WriteLine("=======================================================") Console.WriteLine("Description: {0}", Me.ShowDescription()) Console.WriteLine("-=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=-") Console.WriteLine("Radius: {0}", Me.Radius) Console.WriteLine("Diameter: {0}", Me.CalculateDiameter()) Console.WriteLine("Circumference: {0}" & vbCrLf, Me.CalculateCircumference()) End Sub

End Class

Public Class Sphere Inherits Circle

Protected Overrides Function ShowDescription() Return "A sphere is a three-dimensional geometric " & vbCrLf & _ "shape based on a circle. It is constructed " & vbCrLf & _ "so that all considered points around the shape " & vbCrLf & _ "are at an equal distance from a common point " & vbCrLf & _ "called the center. Like the circle, two equally " & vbCrLf & _ "opposite points from the center are at the exact " & vbCrLf & _ "same dictance from that center." End Function

Public Overrides Sub ShowCharacteristics() ' Because Sphere is based on Circle, you can access ' any public member(s) of Circle without qualifying it(them) Me.Radius = 35.84

Console.WriteLine("Sphere Characteristics") Console.WriteLine("=======================================================") Console.WriteLine("Description: {0}", Me.ShowDescription()) Console.WriteLine("-=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=-") Console.WriteLine("Radius: {0}", Me.Radius) Console.WriteLine("Diameter: {0}", Me.CalculateDiameter()) Console.WriteLine("Circumference: {0}", Me.CalculateCircumference()) Console.WriteLine("=======================================================") End Sub

End Class

File: Exercise.vb

Module Exercise

Public Function Main() As Integer Dim circ As Circle = New Circle circ.ShowCharacteristics()

Dim ball As Sphere = New Sphere ball.ShowCharacteristics()

Return 0 End Function

End Module

Page 321: Microsoft Visual Basic 2010 Tutorial

This would produce:

Circle Characteristics=======================================================Description: A circle is a round geometric shapeconstructed so that all considered points of theshape are at an equal distance from a common pointcalled the center. Also, two equally opposite pointsfrom the center are at the exact same dictance fromthat center.-=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=-Radius: 35.84Diameter: 71.68Circumference: 225.1891712

Sphere Characteristics=======================================================Description: A sphere is a three-dimensional geometricshape based on a circle. It is constructedso that all considered points around the shapeare at an equal distance from a common pointcalled the center. Like the circle, two equallyopposite points from the center are at the exactsame dictance from that center.-=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=-Radius: 35.84Diameter: 71.68Circumference: 225.1891712=======================================================

If you mark as member of a child class with Overrides, it must have a corresponding member inthe parent class and that corresponding member must be marked with the Overridable keyword.

Shadowing a Method

You can notice in the above example that the derived class produces the same results as the baseclass. In reality, inheritance is used to solve various Object-Oriented Programming (OOP)problems. One of them consists of customizing, adapting, or improving the behavior of a feature ofthe parent class. For example, although both the circle and the sphere have an area, their areasare not the same. A circle is a flat surface but a sphere is a volume, which makes its area verymuch higher. Since they use different formulas for their respective area, you should implement anew version of the area in the sphere. This would be done as follows:

Public Class Circle Public Radius As Double

Public Function CalculateArea() As Double Return Radius * Radius * 3.14159 End FunctionEnd Class

Private Class Sphere Inherits Circle

Public Function CalculateArea() As Double Return 4 * Radius * Radius * 3.14159 End Function

End Class

Imagine that, in a method of the Sphere class, you call an Area() method, even if you use Me, itmay not appear clear what Area() you are accessing. If you create a member, such as a method,in the child class and that has the same signature as an existing member of a parent class, tomake sure that you access the derived version of the member, you can hide the correspondingmember of the parent class. To do this, precede the member of the child class with the Shadowskeyword. This would be done as follows:

File: Circle.vb

Public Class Circle

Protected Radius As Double

Protected Overridable Function ShowDescription() Return "A circle is a round geometric shape " & vbCrLf & _ "constructed so that all considered points of the " & vbCrLf & _ "shape are at an equal distance from a common point " & vbCrLf & _ "called the center. Also, two equally opposite points " & vbCrLf & _ "from the center are at the exact same dictance from " & vbCrLf & _ "that center." End Function

Public Function CalculateDiameter() As Double Return Radius * 2 End Function

Public Function CalculateCircumference() As Double Return CalculateDiameter() * 3.14159 End Function

Public Function CalculateArea() As Double Return Radius * Radius * 3.14159 End Function

Page 322: Microsoft Visual Basic 2010 Tutorial

Public Overridable Sub ShowCharacteristics() Me.Radius = 35.84

Console.WriteLine("Circle Characteristics") Console.WriteLine("=======================================================") Console.WriteLine("Description: {0}", Me.ShowDescription()) Console.WriteLine("-=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=-") Console.WriteLine("Radius: {0}", Radius) Console.WriteLine("Diameter: {0}", Me.CalculateDiameter()) Console.WriteLine("Circumference: {0}", Me.CalculateCircumference()) Console.WriteLine("Area: {0}", Me.CalculateArea()) Console.WriteLine("=======================================================") End Sub

End Class

Public Class Sphere Inherits Circle

Protected Overrides Function ShowDescription() Return "A sphere is a three-dimensional geometric " & vbCrLf & _ "shape based on a circle. It is constructed " & vbCrLf & _ "so that all considered points around the shape " & vbCrLf & _ "are at an equal distance from a common point " & vbCrLf & _ "called the center. Like the circle, two equally " & vbCrLf & _ "opposite points from the center are at the exact " & vbCrLf & _ "same dictance from that center." End Function

Public Shadows Function CalculateArea() As Double Return 4 * Radius * Radius * 3.14159 End Function

Public Function CalculateVolume() As Double Return 4 * 3.14159 * Radius * Radius * Radius / 3 End Function

Public Overrides Sub ShowCharacteristics() ' Because Sphere is based on Circle, you can access ' any public member(s) of Circle without qualifying it(them) Me.Radius = 35.84

Console.WriteLine("Sphere Characteristics") Console.WriteLine("=======================================================") Console.WriteLine("Description: {0}", Me.ShowDescription()) Console.WriteLine("-=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=-") Console.WriteLine("Radius: {0}", Me.Radius) Console.WriteLine("Diameter: {0}", Me.CalculateDiameter()) Console.WriteLine("Circumference: {0}", Me.CalculateCircumference()) Console.WriteLine("Area: {0}", Me.CalculateArea()) Console.WriteLine("Volume: {0}", Me.CalculateVolume()) Console.WriteLine("=======================================================") End Sub

End Class

File: Exercise.vb

Module Exercise

Public Function Main() As Integer Dim circ As Circle = New Circle circ.ShowCharacteristics()

Dim ball As Sphere = New Sphere ball.ShowCharacteristics()

Return 0 End Function

End Module

This would produce:

Circle Characteristics=======================================================Description: A circle is a round geometric shapeconstructed so that all considered points of theshape are at an equal distance from a common pointcalled the center. Also, two equally opposite pointsfrom the center are at the exact same dictance fromthat center.-=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=-Radius: 35.84Diameter: 71.68Circumference: 225.1891712Area: 4035.389947904=======================================================Sphere Characteristics=======================================================Description: A sphere is a three-dimensional geometricshape based on a circle. It is constructedso that all considered points around the shapeare at an equal distance from a common pointcalled the center. Like the circle, two equallyopposite points from the center are at the exactsame dictance from that center.-=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=-Radius: 35.84Diameter: 71.68

Page 323: Microsoft Visual Basic 2010 Tutorial

Circumference: 225.1891712Area: 16141.559791616Volume: 192837.834310506=======================================================

Inheritance and the .NET Framework

Object: The Ancestor to all Classes

The .NET Framework is the main library used by the Microsoft Visual Basic .NET programminglanguage. When Visual Basic was developed, inheritance was kept in mind art all levels so that the.NET Framework library provides as much functionality as possible to enhance all types ofapplications necessary. To provide this functionality, the .NET Framework provides a rich set ofclasses (and namespaces as we will see).

At the highest level, the library provides the Object class that serves as the common ancestor toall classes used in the .NET Framework. In fact, any time you create a class to use in your VisualBasic application, the class is automatically derived from Object. Consider the following Squareclass:

Module Exercise Public Class Square Public Side As Double

Function CalculatePerimeter() As Double Return Side * 4 End Function

Function CalculateArea() As Double Return Side * Side End Function End Class

Public Function Main() As Integer Dim sqr As Square = New Square

Console.Write("Enter Side: ") sqr.Side = Double.Parse(Console.ReadLine())

Console.WriteLine() Console.WriteLine("Square Characteristics") Console.WriteLine("Side: {0:F}", sqr.Side) Console.WriteLine("Perimeter: {0:F}", sqr.CalculatePerimeter()) Console.WriteLine("Area: {0:F}", sqr.CalculateArea())

Return 0 End Function

End Module

Here is an example of running the program:

Enter Side: 42.48

Square CharacteristicsSide: 42.48Perimeter: 169.92Area: 1804.55

Although the Square class doesn't indicate that it is inheriting from any class, by virtue ofbelonging to a Visual Basic application, it inherits from Object. For this reason, the above codecould also have been written as follows:

Module Exercise

Public Class Square Inherits Object

End Class

End Module

This would produce the same results. Most of the time, if not always, you don't need to derive aclass from Object: this inheritance is automatic and it is implied. The obvious question would be,"What does Object offer to its descendant?". By itself, the Object class provides little but usefulfunctionality to its children. In fact it is equipped with only half a dozen methods. Still, this littlefunctionality allows the various child class to interact easily or perform some operations that wouldrequire casting.

All of the methods of the Object class are public, making them directly available to thedescendant classes. Most are "Overridable"s, meaning if you want to use them, you shouldimplement your own version in your class.

String Conversion

One of the functionalities provided by the Object class consists of converting a class to a string.

Page 324: Microsoft Visual Basic 2010 Tutorial

Because this can mean different things to different classes. The Object class provides the methodnamed ToString. Its syntax is:

Public Overridable Function ToString() As String

In some cases, you can directly call this method as it is available to your class already. Here is anexample:

Module Exercise Public Class Square Inherits Object

Public Side As Double

Function CalculatePerimeter() As Double Return Side * 4 End Function

Function CalculateArea() As Double Return Side * Side End Function End Class

Public Function Main() As Integer Dim sqr As Square = New Square

sqr.ToString()

Return 0 End Function

End Module

Otherwise, most of the time, you will need to indicate to the compiler how this method should beinterpreted by your class, which is done by overriding it. To override this method, follow the rulesof overriding a method by associating the Overrides keyword with the syntax of the method. Inthe body of the method, implement it as you see fit. Here is an example:

Module Exercise Public Class Square Inherits Object

Public Side As Double

Function CalculatePerimeter() As Double Return Side * 4 End Function

Function CalculateArea() As Double Return Side * Side End Function

Public Overrides Function ToString() As String Return "Square Characteristics" & vbCrLf & _ "Side: " & CStr(Side) & vbCrLf & _ "Perimeter: " & CStr(CalculatePerimeter()) & vbCrLf & _ "Area: " & CStr(CalculateArea()) End Function End Class

End Module

Because the Object.ToString() method returns a String object, you can assign its result to astring or pass it to a function or method that takes a string as argument. Here is an example:

Module Exercise Public Class Square Inherits Object

Public Side As Double

Function CalculatePerimeter() As Double Return Side * 4 End Function

Function CalculateArea() As Double Return Side * Side End Function

Public Overrides Function ToString() As String Return "Square Characteristics" & vbCrLf & _ "Side: " & CStr(Side) & vbCrLf & _ "Perimeter: " & CStr(CalculatePerimeter()) & vbCrLf & _ "Area: " & CStr(CalculateArea()) End Function End Class

Public Function Main() As Integer Dim sqr As Square = New Square

Console.WriteLine(sqr.ToString())

Return 0 End Function

End Module

Page 325: Microsoft Visual Basic 2010 Tutorial

Object and Classes Comparisons

Another valuable method of the Object class is called Equals. This method is used to comparetwo instances of a class for equality. This method is overloaded with two versions and each returnsa Boolean value.

One of the versions of the Object.Equals() method has the following syntax:

Overloads Public Overridable Function Equals(ByVal obj As Object) As Boolean

This method can be called by any class of a .NET Framework application and it takes as argumentan instance of the class that the called needs to be compared to. Here is an example:

Module Exercise

Public Function Main() As Integer Dim number1 As Integer, number2 As Integer

number1 = 248 number2 = 2480 Console.WriteLine("{0} = {1}: {2}", number1, number2, _ number1.Equals(number2))

Return 0 End Function

End Module

This would produce:

248 = 2480: False

The second version of the Object.Equals() method has the following syntax:

Overloads Public Shared Function Equals(ByVal objA As Object,_ ByVal objB As Object) As Boolean

This version is declared as Shared. This means that it is not called by a specific instance of aclass. Instead, it takes two arguments that each represents an instance of the classes that need tobe compared. Here is an example of calling it:

Module Exercise

Public Function Main() As Integer Dim Country As String, Pais As String

Country = "Senegal" Pais = "Senegal" Console.WriteLine("{0} = {1}: {2}", Country, Pais, _ Equals(Country, Pais))

Return 0 End Function

End Module

This would produce:

Senegal = Senegal: True

Although this method is made available to all .NET classes by through inheritance from the Objectclass, in most cases, to make sure it rightly behaves, you should customize its implementation inmost of your classes where you intend to call it. Consider the following program:

Module Exercise Public Class Square Inherits Object

Public Side As Double

Function CalculatePerimeter() As Double Return Side * 4 End Function

Function CalculateArea() As Double Return Side * Side End Function

Public Overrides Function ToString() As String Return "Square Characteristics" & vbCrLf & _ "Side: " & CStr(Side) & vbCrLf & _ "Perimeter: " & CStr(CalculatePerimeter()) & vbCrLf & _ "Area: " & CStr(CalculateArea()) End Function End Class

Public Function Main() As Integer Dim sqr1 As Square = New Square Dim sqr2 As Square = New Square

Console.WriteLine(" =+= First Square =+=") Console.Write("Enter Side: ") sqr1.Side = Double.Parse(Console.ReadLine()) Console.WriteLine(" =+= Second Square =+=")

Page 326: Microsoft Visual Basic 2010 Tutorial

Console.Write("Enter Side: ") sqr2.Side = Double.Parse(Console.ReadLine())

Console.WriteLine() Console.WriteLine("{0}", sqr1.ToString()) Console.WriteLine() Console.WriteLine("{0}", sqr2.ToString()) Console.WriteLine()

Console.WriteLine("Squares Equality: {0}", sqr1.Equals(sqr2))

Return 0 End Function

End Module

Here is an example of executing it:

=+= First Square =+=Enter Side: 125.84 =+= Second Square =+=Enter Side: 125.84

Square CharacteristicsSide: 125.84Perimeter: 503.36Area: 15835.71

Square CharacteristicsSide: 125.84Perimeter: 503.36Area: 15835.71

Squares Equality: False

Notice that, although both square instances have the same Side value and produce the same area,the compiler renders them not equal. This is an indication that the compiler doesn't know how tocompare two instances of the Square class. The solution to this type of problem is to override theEquals() method in your class instead of relying on the default implementation from the Objectclass. Here are two overrides of the Equals() methods as overridden for the above Square class:

Module Exercise Public Class Square Inherits Object

Public Side As Double

Function CalculatePerimeter() As Double Return Side * 4 End Function

Function CalculateArea() As Double Return Side * Side End Function

Public Overrides Function ToString() As String Return "Square Characteristics" & vbCrLf & _ "Side: " & CStr(Side) & vbCrLf & _ "Perimeter: " & CStr(CalculatePerimeter()) & vbCrLf & _ "Area: " & CStr(CalculateArea()) End Function

Public Overridable Overloads Function Equals(ByVal sqr As Square) As Boolean ' We will only compare the side of the square ' because the calculations of the perimeter and the area ' directly depend on the side ' If the side of the square passed as argument is equal ' to the side of this object, both objects are equal If sqr.Side = Me.Side Then Return True ' If the sides are not equal, then the objects are not equal Return False End Function

Public Overloads Shared Function Equals(ByVal first As Square, _ ByVal second As Square) As Boolean ' We will only compare the side of the square ' If the side of the first square is equal ' to the side of the second one, then both squares are equal If first.Side = second.Side Then Return True ' If the sides are not equal, then the objects are not equal Return False End Function End Class

Public Function Main() As Integer Dim sqr1 As Square = New Square Dim sqr2 As Square = New Square

Console.WriteLine(" =+= First Square =+=") Console.Write("Enter Side: ") sqr1.Side = Double.Parse(Console.ReadLine()) Console.WriteLine(" =+= Second Square =+=") Console.Write("Enter Side: ") sqr2.Side = Double.Parse(Console.ReadLine())

Console.WriteLine() Console.WriteLine("{0}", sqr1.ToString()) Console.WriteLine("{0}", sqr2.ToString())

Page 327: Microsoft Visual Basic 2010 Tutorial

Console.WriteLine("Squares Equality: {0}", sqr1.Equals(sqr2))

Console.WriteLine() Console.WriteLine(" =+= First Square =+=") Console.Write("Enter Side: ") sqr1.Side = Double.Parse(Console.ReadLine()) Console.WriteLine(" =+= Second Square =+=") Console.Write("Enter Side: ") sqr2.Side = Double.Parse(Console.ReadLine())

Console.WriteLine() Console.WriteLine("{0}", sqr1.ToString()) Console.WriteLine() Console.WriteLine("{0}", sqr2.ToString()) Console.WriteLine()

Console.WriteLine("Squares Equality: {0}", Equals(sqr1, sqr2))

Return 0 End Function

End Module

Here is an example of testing the program:

=+= First Square =+=Enter Side: 125.84 =+= Second Square =+=Enter Side: 125.84

Square CharacteristicsSide: 125.84Perimeter: 503.36Area: 15835.71

Square CharacteristicsSide: 125.84Perimeter: 503.36Area: 15835.71

Squares Equality: True

=+= First Square =+=Enter Side: 38.45 =+= Second Square =+=Enter Side: 16.82

Square CharacteristicsSide: 38.45Perimeter: 153.80Area: 1478.40

Square CharacteristicsSide: 16.82Perimeter: 67.28Area: 282.91

Squares Equality: False

Here is another run of the same program:

=+= First Square =+=Enter Side: 70.68 =+= Second Square =+=Enter Side: 42.04

Square CharacteristicsSide: 70.68Perimeter: 282.72Area: 4995.66

Square CharacteristicsSide: 42.04Perimeter: 168.16Area: 1767.36

Squares Equality: False

=+= First Square =+=Enter Side: 58.26 =+= Second Square =+=Enter Side: 58.26

Square CharacteristicsSide: 58.26Perimeter: 233.04Area: 3394.23

Square CharacteristicsSide: 58.26Perimeter: 233.04Area: 3394.23

Squares Equality: True

Notice that, this time, the compiler knows how to perform the comparison of two Square objectsusing either version of the Equals() method.

Page 328: Microsoft Visual Basic 2010 Tutorial

The Current Date

Microsoft Visual Basic provides various functions to perform date and time related operations.These functions allow you to add dates or times, find the difference between dates or times, oradd constant values to dates or times.

The current date is represented by a function called Date. The Date() function is used to get thesystem date of the computer. You can use it to display today's date, provided your computer hasthe correct date.

The current time of the computer is represented by a function called Time. The Time() function isused to get the system time of the computer.

The Date() and Time() functions can be combined and are represented by a function called Now.

Previous Copyright © 2008-2010 FunctionX, Inc. Next

Page 329: Microsoft Visual Basic 2010 Tutorial

Class Abstraction

An Abstract Class

Introduction

It should appear to us clearly by now that inheritance is useful by allowing us to use an objectthat was already created but "upgrade" it with new features that were not available when theoriginal object was born. In most cases, when creating a class, you may not thing that otherclasses would be inherited from it. In fact, this will usually not be your concern: you simplycreate a class and use it as needed.

In some other cases, rather as you build your experience with Visual Basic. You may create a classthat, although useful at the time, you may already think of other classes that would be based onit. This means that, at the time you are creating such a class, you would already keep inheritancein mind. Visual Basic provides various features that can assist you with creating and implementingclass with different goals in mind.

Abstracting a Class

Imagine that, when creating a class, you already find that it is too or highly generalized to serveone particular purpose. As an example, imagine you start creating a class you intend to use toprocess calculations for a rectangle, or a square, or a parallelogram, or even a triangle:

Rectangle Square Parallelogram Triangle

You start thinking that the same class could be used for different types of geometric shapes. Inthis case, instead of creating a different class for each shape, you can create a generalized classthat these shapes can be based on. Unfortunately, these shapes, although each characterized asgeometric, don't have much in common; otherwise they would not be different. One of theircommon characteristics is that each has a name. While the parallelogram and the triangle have abase, the rectangle and the square don't explicitly have one. Also, neither the perimeter nor thearea of these shapes are calculated the same. Still, as long as you find at least one characteristicthat these objects have, you can create a class that would share. In other words, you can create aclass that features one or more characteristics that these objects have. Then each object wouldcustomize its behavior(s) based on its particular characteristics. This is the basis of abstraction.

A class is referred to as abstract when it is only used to lay a foundation for other classes. In theMicrosoft Visual Basic language, to create an abstract class, you must precede its Class keywordwith MustInherit. Here is an example:

File: Quadrilateral.vb

Public MustInherit Class Quadrilateral

End Class

After creating a class and marking it as MustInherit, you can add one or more members to it, asdone in the previous examples we used so far. Here is an example:

File: Quadrilateral.vb

Public MustInherit Class Quadrilateral Public Function ShowDescription() As String Return "Geometric Shape" End FunctionEnd Class

If you create a class and mark it as MustInherit, it is considered incomplete. Because of that,although you can declare a variable of that type, you cannot initialize its instance using the Newoperator. Consider the following example:

File: Exercise.vb

Module Exercise

Page 330: Microsoft Visual Basic 2010 Tutorial

Public Function Main() As Integer Dim quad As Quadrilateral = New Quadrilateral

Console.WriteLine("Description = {0}", quad.Description)

Return 0 End Function

End Module

This would produce an error because you cannot use New to instantiate a MustInherit class. Thismeans that, before using a MustInherit class, you must derive a class from it.

Overriding Members of an Abstract Class

The main idea for creating a MustInherit class is to lay a foundation that other classes canexploit. When creating the members of such a class, you can prepare them to be overridden. Youhave the option of creating overridable and non-overridable members. You will make the decisionbased on your requirements.

Sometimes when creating a particular member, you may intend all derived classes to implementtheir own version of the member. You must clearly indicate that any class that wants to inheritfrom the MustInherit class must (also) override a particular member. Such a member must bemarked with the MustOverride keyword. To do this, when creating the member, precede its typewith the MustOverride keyword. Here is an example:

File: Quadrilateral.vb

Public MustInherit Class Quadrilateral Public MustOverride Property Area() As Double

End Class

In the same way, you can add as many members as necessary. You will mark as MustOverridethose of your choice and you can create others without MustOverride. Here are examples:

File: Quadrilateral.vb

Public MustInherit Class Quadrilateral Public Function ShowDescription() As String Return "Geometric Shape" End Function

Public MustOverride Property Area() As DoubleEnd Class

After creating a MustInherit class, you can inherit new classes from it using the Inheritskeyword we saw in the previous lessons. Here is an example:

Public Class Square Inherits Quadrilateral

End Class

When deriving a class from a MustInherit, the first rule you must observe is that each member ofthe abstract that was marked as MustOverride must be overridden. Based on this, in our Squareclass, you must (at least) implement the Area property. Here is an example:

File: Quadrilateral.vb

Public MustInherit Class Quadrilateral Public Function ShowDescription() As String Return "Geometric Shape" End Function

Public MustOverride ReadOnly Property Area() As DoubleEnd Class

Public Class Square Inherits Quadrilateral

Public Overrides ReadOnly Property Area() As Double Get Return 0 End Get End PropertyEnd Class

In the derived class, as a new one, you can add new members as you judge them necessary. Hereare examples:

File: Quadrilateral.vb

Public MustInherit Class Quadrilateral Public Function ShowDescription() As String Return "Geometric Shape" End Function

Page 331: Microsoft Visual Basic 2010 Tutorial

Public MustOverride ReadOnly Property Area() As DoubleEnd Class

Public Class Square Inherits Quadrilateral

Public sd As Double

Public Sub New() sd = 0 End Sub

Public Sub New(ByVal side As Double) sd = side End Sub

Public Property Side() As Double Get Return sd End Get Set(ByVal Value As Double) If Value <= 0 Then sd = 0 Else sd = Value End If End Set End Property

Public Overrides ReadOnly Property Area() As Double Get Return sd * sd End Get End PropertyEnd Class

After deriving a new class from a MustInherit class, you can declare a variable of it andinstantiate it using the New operator. Here is an example:

File: Exercise.vb

Module Exercise

Public Function Main() As Integer Dim sqr As Square = New Square

sqr.Side = 35.75

Console.WriteLine(" -=- Square Characteristics -=-") Console.WriteLine("Description: {0}", sqr.ShowDescription) Console.WriteLine("Side: {0}", sqr.Side) Console.WriteLine("Area: {0}", sqr.Area)

Return 0 End Function

End Module

This would produce:

-=- Square Characteristics -=-Description: Geometric ShapeSide: 35.75Area: 1278.0625

As mentioned earlier, after creating a MustInherit class, you can declare a variable of it but youcannot instantiate it using the New operator. Consider the following example:

Module Exercise

Public Function Main() As Integer Dim sqr As Quadrilateral sqr = New Square

Return 0 End Function

End Module

These declaration and instantiation are legal but the (tri) variable gives you access only tomembers that are present in the parent class. This means that this declaration gives you access tothe ShowDescription() method and the Area property of the Quadrilateral class. This is illustratedin the following:

Module Exercise

Public Function Main() As Integer Dim sqr As Quadrilateral sqr = New Square

Console.WriteLine(" -=- Square Characteristics -=-") Console.WriteLine("Description: {0}", sqr.ShowDescription) Console.WriteLine("Area: {0}", sqr.Area)

Return 0 End Function

Page 332: Microsoft Visual Basic 2010 Tutorial

End Module

This would produce:

-=- Square Characteristics -=-Description: Geometric ShapeArea: 0

When instantiating a class derived from a MustInherit class, if you want to access its members,you must apply its name to the New operator as we saw in the last example of the previoussection. Here is an example:

Module Exercise

Public Function Main() As Integer Dim sqr As Square = New Square(42.68)

Console.WriteLine(" -=- Square Characteristics -=-") Console.WriteLine("Description: {0}", sqr.ShowDescription) Console.WriteLine("Side: {0}", sqr.Side) Console.WriteLine("Area: {0}", sqr.Area)

Return 0 End Function

End Module

This would produce:

-=- Square Characteristics -=-Description: Geometric ShapeSide: 42.68Area: 1821.5824

Sealed Classes

All of the classes we have used so far can serve as parents of other classes. This is the defaultbehavior of a regular class: the ability to derive a new class from it. In some cases, you may notwant any class to be derived from a particular class you are creating. Such a class is referred to assealed.

A class is said to be sealed when you cannot inherit from it. If you try, you would receive an error.To create a sealed class in Microsoft Visual Basic, precede the name of the class with theNotInheritable keyword.

Interfaces

Introduction

We described abstract classes as those intended for inheritance. Another type of class designed forthis purpose is referred to as an interface. An interface is a class that creates a foundation thatnew derived classes can use. As done for an abstract class, you can create original behavior thatthe deriving classes would use. Unlike abstract classes, you don't implement the members(properties and procedures) of the interface. The general idea of an interface is only to lay afoundation, as creating a structural base, that the new classes would follow, although they cancustomize the behavior(s) of the parent interface but the parent interface does not "decide" whatthe behavior of a member would be.

Interface Creation

To create an interface, you start with the Interface keyword followed by the name of theinterface. You end the interface definition with an End Interface line. By tradition or good habit,the name of an interface starts with I. Here is an example of a starting interface:

File: RegularTriangle.vb

Public Interface ITriangle

End Interface

After creating an interface, you can derive a class from it. When deriving from an interface, insteadof the Inherits keyword, you use Implements followed by the name of the interface. Here is anexample of a new class named Regular and that is based on the above ITriangle interface:

File: RegularTriangle.vb

Public Interface ITriangle

End Interface

Public Class RegularTriangle Implements ITriangle

Page 333: Microsoft Visual Basic 2010 Tutorial

End Class

As with other classes, once you have derived the class, you can create objects from it andinstantiate it using the New operator. Here is an example:

File: Exercise.vb

Module Exercise

Public Function Main() As Integer Dim reg As RegularTriangle reg = New RegularTriangle

Return 0 End Function

End Module

As mentioned earlier, the purpose of having an interface is to create a skeleton that derivedclasses would follow. To do this, in the body of the interface, you can create the necessarymembers that you want to make available to new classes. The members can be the same types ofmethods or properties as those we have used in classes so far. Here are examples:

File: RegularTriangle.vb

Public Interface ITriangle ReadOnly Property Name() As String Property Base() As Double Property Height() As Double

Function CalculatePerimeter() As Double Function CalculateArea() As DoubleEnd Interface

The primary rule you must observe when deriving a class from an interface is that you mustimplement each member of the interface in the derived class. If you omit implementing a memberof the parent interface, you would receive an error. When implementing a member of theinterface, it must be followed by the Implements keyword, the name of the interface, the periodoperator, and the name of the member that it is implementing. Based on this, our Regular classcan implement the ITriangle interface as follows:

File: RegularTriangle.vb

Public Interface ITriangle ReadOnly Property Name() As String Property Base() As Double Property Height() As Double

Function CalculatePerimeter() As Double Function CalculateArea() As DoubleEnd Interface

Public Class RegularTriangle Implements ITriangle

Public bas As Double Public hgt As Double Public sd1 As Double Public sd2 As Double

' Default constructor: the user will specify the dimensions Public Sub New() bas = 0 hgt = 0 sd1 = 0 sd2 = 0 End Sub

' A triangle based on known base and height Public Sub New(ByVal b As Double, ByVal h As Double) bas = b hgt = h End Sub

' A triangle based on the measurements of the sides Public Sub New(ByVal b As Double, ByVal side1 As Double, ByVal side2 As Double) bas = b sd1 = side1 sd2 = side2 End Sub

' A triangle whose all sides and the height are known Public Sub New(ByVal b As Double, ByVal h As Double, _ ByVal side1 As Double, ByVal side2 As Double) bas = b hgt = h sd1 = side1 sd2 = side2 End Sub

Public Property Base() As Double Implements ITriangle.Base Get Return bas End Get

Page 334: Microsoft Visual Basic 2010 Tutorial

Set(ByVal Value As Double) If bas < 0 Then bas = 0 Else bas = Value End If End Set End Property

Public Function CalculateArea() As Double Implements ITriangle.CalculateArea Return bas * hgt / 2 End Function

Public Function CalculatePerimeter() As Double Implements _ ITriangle.CalculatePerimeter Return bas + sd1 + sd2 End Function

Public Property Height() As Double Implements ITriangle.Height Get Return hgt End Get Set(ByVal Value As Double) If hgt < 0 Then hgt = 0 Else hgt = Value End If End Set End Property

Public ReadOnly Property Name() As String Implements ITriangle.Name Get Return "Regular Triangle" End Get End Property

End Class

Once the class has been defined like this, you can then instantiate and use it. Here is an example:

File: Exercise.vb

Module Exercise

Public Function Main() As Integer Dim reg As RegularTriangle = New RegularTriangle(35.28, 26.44)

Console.WriteLine("Triangle Type: {0}", reg.Name) Console.WriteLine("=-= Characteristics =-=") Console.WriteLine("Base: {0}", reg.Base) Console.WriteLine("Height: {0}", reg.Height) Console.WriteLine("Area: {0}", reg.CalculateArea)

Return 0 End Function

End Module

This would produce:

Triangle Type: Regular Triangle=-= Characteristics =-=Base: 35.28Height: 26.44Area: 466.4016

In the same way, you can derive other classes from an interface. For example, from our ITriangleclass, you can derive an isosceles, a right, or an equilateral triangle. Always remember that whenyou derive a class, you must implement all of the members of the interface. You can also add newmembers as you see fit.

An Interface Derived

Like a regular class, an interface can be derived from another interface but an interface cannotderive from a class. To create an interface based on another, use the Inherits keyword as we haveused in other classes. Here is an example:

File: RegularTriangle.vb

Public Interface IGeometricShape

End Interface

Public Interface ITriangle Inherits IGeometricShape

End Interface

As mentioned for the interfaces, you can use the parent interface to list the members that thederiving classes would implement. Still remember that since an interface cannot implement amember, the member of the parent interface cannot be defined in a derived interface. Thisimplement would wait for the actual class(es) that would be based on the child (or even theparent) interface. Here is an example:

Page 335: Microsoft Visual Basic 2010 Tutorial

File: RegularTriangle.vb

Public Interface IGeometricShape ReadOnly Property Type() As StringEnd Interface

Public Interface ITriangle Inherits IGeometricShape

ReadOnly Property Name() As String Property Base() As Double Property Height() As Double

Function CalculatePerimeter() As Double Function CalculateArea() As DoubleEnd Interface

After deriving a class from an interface, when defining the class, you must implement the memberof the immediate interface and those of the ancestor interface(s). Here is an example:

File: RegularTriangle.vb

Public Interface IGeometricShape ReadOnly Property Type() As StringEnd Interface

Public Interface ITriangle Inherits IGeometricShape

ReadOnly Property Name() As String Property Base() As Double Property Height() As Double

Function CalculatePerimeter() As Double Function CalculateArea() As DoubleEnd Interface

Public Class RegularTriangle Implements ITriangle

Public bas As Double Public hgt As Double Public sd1 As Double Public sd2 As Double

Public ReadOnly Property Type() As String Implements ITriangle.type Get Return "Triangle" End Get End Property

' Default constructor: the user will specify the dimensions Public Sub New() bas = 0 hgt = 0 sd1 = 0 sd2 = 0 End Sub

' A triangle based on known base and height Public Sub New(ByVal b As Double, ByVal h As Double) bas = b hgt = h End Sub

' A triangle based on the measurements of the sides Public Sub New(ByVal b As Double, ByVal side1 As Double, ByVal side2 As Double) bas = b sd1 = side1 sd2 = side2 End Sub

' A triangle whose all sides and the height are known Public Sub New(ByVal b As Double, ByVal h As Double, _ ByVal side1 As Double, ByVal side2 As Double) bas = b hgt = h sd1 = side1 sd2 = side2 End Sub

Public Property Base() As Double Implements ITriangle.Base Get Return bas End Get Set(ByVal Value As Double) If bas < 0 Then bas = 0 Else bas = Value End If End Set End Property

Public Function CalculateArea() As Double Implements ITriangle.CalculateArea Return bas * hgt / 2 End Function

Page 336: Microsoft Visual Basic 2010 Tutorial

Public Function CalculatePerimeter() As Double Implements _ ITriangle.CalculatePerimeter Return bas + sd1 + sd2 End Function

Public Property Height() As Double Implements ITriangle.Height Get Return hgt End Get Set(ByVal Value As Double) If hgt < 0 Then hgt = 0 Else hgt = Value End If End Set End Property

Public ReadOnly Property Name() As String Implements ITriangle.Name Get Return "Regular" End Get End PropertyEnd Class

Here is an example of testing the class:

File: Exercise.vb

Module Exercise

Public Function Main() As Integer Dim reg As RegularTriangle = New RegularTriangle(35.28, 26.44)

Console.WriteLine("Shape Type: {0}", reg.Type) Console.WriteLine("Triangle Type: {0}", reg.Name) Console.WriteLine("=-= Characteristics =-=") Console.WriteLine("Base: {0}", reg.Base) Console.WriteLine("Height: {0}", reg.Height) Console.WriteLine("Area: {0}", reg.CalculateArea)

Return 0 End Function

End Module

This would produce:

Shape Type: TriangleTriangle Type: Regular=-= Characteristics =-=Base: 35.28Height: 26.44Area: 466.4016

Multiple Inheritance

Multiple inheritance consists of creating a class that is based on more than one parent. In theMicrosoft Visual Basic language (in fact in the .NET Framework), you cannot derive a class frommore than one class. This functionality is available only with interfaces.

To create a class based on more than one interface, after the Implements keyword, enter thename of each interface and separate them with commas. Here is an example:

Public Interface IGeometricShape ReadOnly Property Type() As StringEnd Interface

Public Interface ICalculation

End Interface

Public Interface ITriangle Inherits IGeometricShape, ICalculation

End Interface

The same rules apply for multiple inheritance: you must implements all members of each parentinterface.

Besides deriving from an interface, you can also create a class that is based on a class and one ormore interfaces. To do this, under the line that specifies the name of the class, use the Inheritskeyword to specify the name of the parent, press Enter, and use the Implements keyword tospecify the name of the class that serves as the parent interface. Here is an example:

Public Interface IGeometricShape ReadOnly Property Type() As StringEnd Interface

Public Interface ICalculation

End Interface

Page 337: Microsoft Visual Basic 2010 Tutorial

Public Class Geometry

End Class

Public Interface ITriangle Inherits IGeometricShape, ICalculation

End Interface

Public Class RegularTriangle Inherits Geometry Implements ITriangle

End Class

In the same way, you can create a class that is based on more than one interface but it can bebased on only one class.

Classes and Procedures

Introduction

In Lesson 5, we saw that a procedure was an assignment that complemented a program. We alsosaw that there were two types of procedures: functions and sub routines. These concepts of subprocedures and functions also apply to classes. This means that a procedure that process a class,it can be passed a class as argument, and it can return a class.

As described in Lesson 8, to create a sub procedure, type the Sub keyword followed by a name,followed by parentheses and an end of line. To indicate the end of a sub procedure, you must typeEnd Sub. Therefore, the syntax of a sub procedure is:

Sub ProcedureName()

End Sub

Between the Sub and the End Sub lines, you can declare the necessary variables and they can beof regular types or based on classes. Here is an example:

Module Exercise Private Sub ShowCharacteristics() Dim reg As RegularTriangle = New RegularTriangle(35.28, 26.44)

End Sub

Public Function Main() As Integer

Return 0 End Function

End Module

After declaring a variable based on a class, you can regularly use it as we have done with objectsin the Main() function so far. Here is an example:

File: Exercise.vb

Module Exercise Private Sub ShowCharacteristics() Dim reg As RegularTriangle = New RegularTriangle(35.28, 26.44)

Console.WriteLine("Shape Type: {0}", reg.Type) Console.WriteLine("Triangle Type: {0}", reg.Name) Console.WriteLine("=-= Characteristics =-=") Console.WriteLine("Base: {0}", reg.Base) Console.WriteLine("Height: {0}", reg.Height) Console.WriteLine("Area: {0}", reg.CalculateArea) End Sub

Public Function Main() As Integer ShowCharacteristics()

Return 0 End Function

End Module

In the same way, you can declare as many class variables as you see fit in a procedure.

Returning an Object

So far, as we have learned since Lesson, we know that a function can be used to return a value.In the same way, you can create a function that returns an object of a class. When creating such afunction, set its type as that of the class it would return. The formula to follow is still:

Function FunctionName() As ClassName End Function

In the body of the class, which is the section between the Function and the End Function lines,

Page 338: Microsoft Visual Basic 2010 Tutorial

you can perform any assignment you judge necessary. For example you can declare local variables.Before exiting the function, you must make sure it returns a value based on its As type. You cando this using the Return keyword followed by the value to return. Here is an example:

Private Function CreateTriangle() As RegularTriangle Dim regTri As RegularTriangle Dim base As Double, height As Double

Console.WriteLine("Enter the measurements of the triangle") Console.Write("Base: ") base = CDbl(Console.ReadLine()) Console.Write("Height: ") height = CDbl(Console.ReadLine())

regTri = New RegularTriangle(base, height) Return regTriEnd Function

After defining the function, since it returns a value, when calling it, you can assign it to a variableof the type that it returns. Here is an example:

Module Exercise Private Function CreateTriangle() As RegularTriangle Dim regTri As RegularTriangle Dim base As Double, height As Double

Console.WriteLine("Enter the measurements of the triangle") Console.Write("Base: ") base = CDbl(Console.ReadLine()) Console.Write("Height: ") height = CDbl(Console.ReadLine())

regTri = New RegularTriangle(base, height) Return regTri End Function

Private Sub ShowCharacteristics() Dim reg As RegularTriangle = New RegularTriangle

reg = CreateTriangle()

Console.WriteLine("Shape Type: {0}", reg.Type) Console.WriteLine("Triangle Type: {0}", reg.Name) Console.WriteLine("=-= Characteristics =-=") Console.WriteLine("Base: {0}", reg.Base) Console.WriteLine("Height: {0}", reg.Height) Console.WriteLine("Area: {0}", reg.CalculateArea) End Sub

Public Function Main() As Integer ShowCharacteristics

Return 0 End Function

End Module

Here is a test of the above code:

Enter the measurements of the triangleBase: 18.44Height: 12.62

Shape Type: TriangleTriangle Type: Regular=-= Characteristics =-=Base: 18.44Height: 12.62Area: 116.3564

Passing a Class as Argument

Like a regular variable, a class can be passed as argument to a procedure. When a procedurereceives such an argument, it can process it as necessary. All the rules we reviewed for regularvariables apply to a class, as long as you keep in mind that an object has members that you mayneed to be aware of. When calling the procedure, make sure you pass it a value argument basedon the class it passed to it. Here is an example of a class passed as argument:

Module Exercise Private Function CreateTriangle() As RegularTriangle Dim regTri As RegularTriangle Dim base As Double, height As Double

Console.WriteLine("Enter the measurements of the triangle") Console.Write("Base: ") base = CDbl(Console.ReadLine()) Console.Write("Height: ") height = CDbl(Console.ReadLine())

regTri = New RegularTriangle(base, height) Return regTri End Function

Private Sub ShowCharacteristics(ByVal reg As RegularTriangle) Console.WriteLine("Shape Type: {0}", reg.Type) Console.WriteLine("Triangle Type: {0}", reg.Name)

Page 339: Microsoft Visual Basic 2010 Tutorial

Console.WriteLine("=-= Characteristics =-=") Console.WriteLine("Base: {0}", reg.Base) Console.WriteLine("Height: {0}", reg.Height) Console.WriteLine("Area: {0}", reg.CalculateArea) End Sub

Public Function Main() As Integer Dim Angle3 = CreateTriangle() Console.WriteLine() ShowCharacteristics(Angle3) Console.WriteLine()

Return 0 End Function

End Module

Besides the function, in Lesson 5, we saw that, by passing an argument by reference, a subprocedure could return a value. This characteristic also applies to a class passed as argument.When passing the argument, precede it with the ByRef keyword. In the procedure, process theargument as you see fit, unless you choose not to. When calling the procedure, pass it a validvariable based on the type of the argument. Here is an example:

Module Exercise Private Sub CreateTriangle(ByRef regTri As RegularTriangle) Dim base As Double, height As Double

Console.WriteLine("Enter the measurements of the triangle") Console.Write("Base: ") base = CDbl(Console.ReadLine()) Console.Write("Height: ") height = CDbl(Console.ReadLine())

regTri = New RegularTriangle(base, height) End Sub

Private Sub ShowCharacteristics(ByVal reg As RegularTriangle) Console.WriteLine("Shape Type: {0}", reg.Type) Console.WriteLine("Triangle Type: {0}", reg.Name) Console.WriteLine("=-= Characteristics =-=") Console.WriteLine("Base: {0}", reg.Base) Console.WriteLine("Height: {0}", reg.Height) Console.WriteLine("Area: {0}", reg.CalculateArea) End Sub

Public Function Main() As Integer Dim Angle3 As RegularTriangle = New RegularTriangle

CreateTriangle(Angle3) Console.WriteLine() ShowCharacteristics(Angle3) Console.WriteLine()

Return 0 End Function

End Module

Here is an example of testing it:

Enter the measurements of the triangleBase: 50.05Height: 25.52

Shape Type: TriangleTriangle Type: Regular=-= Characteristics =-=Base: 50.05Height: 25.52Area: 638.638

Technique of Using Variables and Arguments

Static Variables

Like a regular variable, a class can be locally declared as static, using the Static keyword. If thevalue of such a locally declared variable changes, when the procedure ends, the value of thevariable is changed and would be kept until the next call.

Optional Arguments

When passing an argument of a class, you can specify that it is not required. Such an argument isconsidered optional. To specify that an argument is optional, when creating its procedure, type theOptional keyword to the left of the argument's name and assign it the default value. All the otherrules we reviewed for optional arguments are also applied here.

Procedure Overloading

If you want to create various procedures that takes a class argument, you can create a procedurewith the same name but different signatures. This is referred to as overloading the procedure.When doing this, follow the same rules we reviewed for overloading a procedure: the must have

Page 340: Microsoft Visual Basic 2010 Tutorial

the same name, they cannot have the same number of argument when the arguments at eachposition are of the same types.

Previous Copyright © 2009-2010 FunctionX, Inc. Home

Page 341: Microsoft Visual Basic 2010 Tutorial

Built-In Classes: The Object Class

Introduction

The .NET Framework is a huge library made of various classes and constants you can directly usein your application without necessarily explicitly loading an external library. To start, this mainlibrary provides a class called Object.

When you create a class, it automatically inherits its primary characteristics from the parent of allclasses: Object.

Equality of Two Class Variables

When you declare and initialize two variables, one of the operations you may want to subsequentlyperform is to compare their value. To support this operation, the Object class provides its childrenwith a method called Equals. The Equals() method comes in two versions. The first has thefollowing syntax:

Public Overridable Function Equals(obj As Object) As Boolean

This version allows you to call the Equals() method on a declared variable and pass the othervariable as argument. Here is an example:

Imports System

Module Exercise

Public Function Main() As Integer ' First book Dim NumberOfPages1 As Integer = 422 ' Second book Dim NumberOfPages2 As Integer = 858 ' Third book Dim NumberOfPages3 As Integer = 422

If NumberOfPages1.Equals(NumberOfPages2) = True Then Console.WriteLine("The first and the second books " & _ "have the same number of pages") Else Console.WriteLine("The first and the second books " & _ "have different number of pages") End If

If NumberOfPages1.Equals(NumberOfPages3) = True Then Console.WriteLine("The first and the third books " & _ "have the same number of pages") Else Console.WriteLine("The first and the third books " & _ "have different number of pages") End If

Return 0 End Function

End Module

This would produce:

The first and the second books have different number of pagesThe first and the third books have the same number of pages

The first version of the Object.Equals method is declared as Overridable, which means you canoverride it if you create your own class. The second version of the Object.Equals() method is:

Public Shared Function Equals(objA As Object, objB As Object) As Boolean

As a Shared method, to use it, you can pass the variables of the two classes whose values youwant to compare.

In both cases, if the values of the variables are similar, the Equals() method returns true. If theyare different, the method returns false. If you are using the Equals() method to compare thevariables of two primitive types, the comparison should be straight forward. If you want to use thismethods on variables declared from your own class, you should provide your own implementationof this method.

Stringing a Class

Page 342: Microsoft Visual Basic 2010 Tutorial

In previous lessons, we learned that, to convert the value of a variable declared from a primitivetype to a string, you could call the ToString() function. Here is an example:

Imports System

Module Exercise

Public Function Main() As Integer Dim NumberOfPages As Integer = 422

Console.Write("Number of Pages: ") Console.WriteLine(NumberOfPages.ToString()) Return 0 End Function

End Module

In many programming languages, programmers usually have to overload an (extractor) operatorto display the value(s) of class' variable to the screen. The Object class provides an alternative tothis somewhat complicated solution, through the ToString() method. It syntax is:

Public Overridable Function ToString As String

Although the Object class provides this method as non abstract, its implemented version is moreuseful if you use a primitive type such as Integer, Double and their variances or a stringvariable. The best way to rely on it consists of overriding it in your own class if you desire to useits role.

Boxing and Un-Boxing

When we study inheritance, we will learn that all data types used in a C# program are "based on"an object called object. As introduced earlier, you can use this data type to declare a variable thatwould hold any type of value. Because this is some type of a "universal" data type, it can also beinitialized with any value. Here are examples:

Imports System

Module Exercise

Public Function Main() As Integer Dim Number As Object Dim Thing As Object

Number = 244 Thing = "Professor Kabba"

Console.WriteLine(Number) Console.WriteLine(Thing) Return 0 End Function

End Module

This would produce:

244Professor Kabba

As you can see, when an object variable is initialized, the compiler finds out the type of value thatwas assigned to it. This is referred to as boxing. This mechanism is transparently done in VisualBasic.

If you declare a variable using a primitive data type (Integer, Single, Double, etc), at one time,you may be interested in converting the value of that variable into an Object. Here is an example:

Imports System

Module Exercise

Public Function Main() As Integer Dim Number As Integer = 244 Dim Thing As Object = Number

Number = 244 Thing = Number

Console.WriteLine(Number) Console.WriteLine(Thing) Return 0 End Function

End Module

This would produce:

244244

This operation is referred to as unboxing. As you can see, this operation is performedtransparently.

Page 343: Microsoft Visual Basic 2010 Tutorial

Finalizing a Variable

While a constructor, created for each class, is used to instantiate a class. The Object classprovides the Finalize() method as a type of destructor.

Home Copyright © 2008-2010 FunctionX, Inc.

Page 344: Microsoft Visual Basic 2010 Tutorial

Built-In Classes: The Random Class

Introduction

Imagine you have a series of numbers, such these: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,15, 16, 17, 18, 19, and 20. Imagine you want to select one of these numbers, any of them. Anumber is referred to as random if it has been selected from a pool without a specific pattern tofollow. For example, if you decide to select the value 17 from this list, if there was an exactreason that number was selected, then it is not considered random. In reality, it is difficult for anumber to qualify as random. For this reason, most random numbers are referred to as pseudo-random.

Getting a Random Number

To support the ability to create or choose a random number, the .NET Framework provides theRandom class. To start, you can declare a variable of this class, using one of its two constructors.Here is an example that uses the default constructor:

Module Exercise

Public Function Main() As Integer Dim rndNumbers As Random = New Random

Return 0 End Function

End Module

After declaring the variable, you can start getting numbers from it. To do this, you call the Next()method, which is overloaded in three versions. One of the versions of this method takes noargument and its syntax is:

Public Overridable Function Next As Integer

This method generates a randomly selected integer between 0 and the MinValue value of theInteger data type. Here is an example:

REM Imports System

Module Exercise

Public Function Main() As Integer Dim rndNumbers As Random = New Random Dim rndNumber As Integer = rndNumbers.Next()

Console.Write("Number: ") Console.WriteLine(rndNumber.ToString())

Return 0 End Function

End Module

Here is an example of running the program:

Number: 1369872590Press any key to continue . . .

In the same way, you can call this version of the Next() method repeatedly to get random. Hereis an example:

Module Exercise

Public Function Main() As Integer Dim nbr As Integer Dim rndNumber As Integer = 0 Dim rndNumbers As Random = New Random

For nbr = 1 To 9 rndNumber = rndNumbers.Next() Console.Write("Number: ") Console.WriteLine(rndNumber.ToString()) Next

Return 0 End Function

End Module

Here is an example of running the program:

Number: 1924504148Number: 1257846191

Page 345: Microsoft Visual Basic 2010 Tutorial

Number: 424740120Number: 1009211682Number: 544356245Number: 708951978Number: 759684741Number: 1325535324Press any key to continue . . .

The Seed of a Random Number

Consider the following program:

Module Exercise

Public Function Main() As Integer Dim rndNumbers As Random = New Random Dim rndNumber As Integer = rndNumbers.Next()

Console.Write("Number: ") Console.WriteLine(rndNumber.ToString())

Return 0 End Function

End Module

Here is an example of running the program:

Number: 573991745Press any key to continue . . .

Here is another example of running the same program:

Number: 334223329Press any key to continue . . .

Notice that the numbers generated are different. When creating a program that repeatedly gets aseries of random numbers, you may (or may not) want the Random class to generate the samenumber over and over again. A seed is a constant value that controls whether a randomgeneration would produce the same result every time it occurs. For example, using a seed, you canimpose it upon the Random class to generate the same number every time the Next() method iscalled. To support the ability to use a seed, the Random class is equipped with a secondconstructor whose syntax is:

Public Sub New(Seed As Integer)

Based on this, to specify a seed, when declaring a Random variable, pass a constant integer tothe constructor. Here is an example:

Module Exercise

Public Function Main() As Integer Dim rndNumbers As Random = New Random(20) Dim rndNumber As Integer = rndNumbers.Next()

Console.WriteLine("Number: {0}", rndNumber)

Return 0 End Function

End Module

Here is one example of running the program:

Number: 375271809Press any key to continue . . .

Here is another example of running the same program:

Number: 375271809Press any key to continue . . .

Notice that the numbers are the same. Consider this program also:

REM Imports System

Module Exercise

Public Function Main() As Integer Dim nbr As Integer Dim rndNumber As Integer = 0 Dim rndNumbers As Random = New Random(20)

For nbr = 1 To 5 rndNumber = rndNumbers.Next() Console.Write("Number: ") Console.WriteLine(rndNumber.ToString()) Next

Return 0 End Function

End Module

Page 346: Microsoft Visual Basic 2010 Tutorial

Here is one example of running the program:

Number: 375271809Number: 1472524622Number: 1605850688Number: 1776011503Press any key to continue . . .

Here is another example of running the same program:

Number: 375271809Number: 1472524622Number: 1605850688Number: 1776011503Press any key to continue . . .

Notice that the sequences are the same. In both cases, this indicates that, if you specify a seed,the Random class would generate the same number or the same sequence of numbers.

Generating Random Numbers in a Range of Numbers

So far, we have been using any number that would fit an integer. In some assignments, you maywant to restrict the range of numbers that can be extracted. Fortunately, the Random class allowsthis. Using the Random class, you can generate random positive numbers up to a maximum ofyour choice. To support this, the Random class is equipped with another version of the Next()method whose syntax is:

Public Overridable Function Next(maxValue As Integer) As Integer

The argument to pass to the method determines the highest integer that can be generated by theNext() method. The method returns an integer. Here is an example that generates randomnumbers from 0 to 20:

REM Imports System

Module Exercise

Public Function Main() As Integer Dim nbr As Integer Dim rndNumber As Integer = 0 Dim rndNumbers As Random = New Random

For nbr = 1 To 9 rndNumber = rndNumbers.Next(20) Console.Write("Number: ") Console.WriteLine(rndNumber.ToString()) Next

Return 0 End Function

End Module

Here is an example of running the program:

Number: 1Number: 7Number: 1Number: 16Number: 14Number: 19Number: 3Number: 1Press any key to continue . . .

The above version of the Next() method generates numbers starting at 0. If you want, you canspecify the minimum and the maximum range of numbers that the Next() method must workwith. To support this, the Random class is equipped with one more version of this method and thattakes two arguments. Its syntax is:

Public Overridable Function Next(minValue As Integer, _ maxValue As Integer) As Integer

The first argument specifies the lowest value that can come from the range. The second argumentholds the highest value that the Next() method can generate. Therefore, the method wouldoperate between both values. Here is an example that generates random numbers from 6 to 18:

Module Exercise

Public Function Main() As Integer Dim nbr As Integer Dim rndNumber As Integer = 0 Dim rndNumbers As Random = New Random

For nbr = 1 To 9 rndNumber = rndNumbers.Next(6, 18) Console.Write("Number: ")

Page 347: Microsoft Visual Basic 2010 Tutorial

Console.WriteLine(rndNumber.ToString()) Next

Return 0 End Function

End Module

Here is an example of running the program:

Number: 17Number: 9Number: 8Number: 15Number: 10Number: 9Number: 13Number: 11Press any key to continue . . .

Home Copyright © 2009-2010 FunctionX, Inc.

Page 348: Microsoft Visual Basic 2010 Tutorial

Dates and Times in Visual Basic

Fundamentals of Dates

Introduction

The Visual Basic language has a strong support for date values. It is equipped with its own datatype named Date. To create and manipulate dates, you have various options. To declare a datevariable, you can use either the Date or the DateTime data types.

While Date is a true data type, DateTime is a class but, even though we have not studiedclasses yet, we can start using DateTime. We will restrict ourselves to using it only as adata type.

We know how to declare a date variable using Date. We also know that, if you already know thecomponents of the date value you want to use, you can include them between two # signs butfollowing the rules of a date format from the Regional Settings of Control Panel. Here is anexample:

Public Module Exercise

Public Function Main() As Integer Dim DateHired As Date

DateHired = # 02/08/2003 #

MsgBox("Date Hired: " & DateHired) Return 0 End Function

End Module

This would produce:

The Parts of a Date Value

When you compose a date value, you must follow some rules. The rules depend on thelanguage you are using. We will review those of the US English.

In a year, a month is recognized by an index in a range from 1 to 12. A month also has aname. The name of a month is given in two formats: complete or short. These are:

MonthIndex Complete Name Short Name

1 January Jan

2 February Feb

3 March Mar

4 April Apr

5 May May

6 June Jun

7 July Jul

8 August Aug

9 September Sep

10 October Oct

11 November Nov

12 December Dec

A week is a combination of 7 consecutive days of a month. Each day can be recognized by anindex from 1 to 7 (1, 2, 3, 4, 5, 6, 7). The day of each index is recognized by a name. In US

Page 349: Microsoft Visual Basic 2010 Tutorial

English, the first day has an index of 1 is named Sunday while the last day with an index of 7is named Monday. Like the months of a year, the days of a week have long and short names.These are:

US English DayIndex Complete Name Short

Name

1 Sunday Sun

2 Monday Mon

3 Tuesday Tue

4 Wednesday Wed

5 Thursday Thu

6 Friday Fri

7 Saturday Sat

These are the default in US English. In most calculations, the Visual Basic language allows youto specify what day should be the first in a week.

The year is expressed as a numeric value.

Dates Formats

In US English, to express a date value, you can use one of the following formats:

mm-dd-yy

mm-dd-yyyy

You must start the date with a number that represents the month (a number from 1 to 12).After the month value, enter -. Then type the day value as a number between 1 and 28, 29,30, or 31 depending on the month and the (leap) year. Follow it with -. End the value with ayear in 2 or 4 digits. Here are examples 06-12-08 or 10-08-2006.

You can also use one of the following formats:

dd-mmm-yy

dd mmm yy

dd-mmmm-yy

dd mmmm yy

dd-mmm-yyyy

dd mmm yyyy

dd-mmmm-yyyy

dd mmmm yyyy

This time, enter the day value followed either by an empty space or -. Follow with the shortname of the month in the mmm placeholder or the complete name of the month for themmmm placeholder, followed by either an empty space or -. End the value with the year, using2 or 4 digits.

As you may know already, in US English, you can start a date with the month. In this case, youcan use one of the following formats:

mmm dd, yy

mmm dd, yyyy

mmmm dd, yy

mmmm dd, yyyy

As seen with the previous formats, mmm represents the short name of a month and mmmmrepresents the complete name of a month. As mentioned already, the dd day can be expressedwith 1 or 2 digits and the single digit can have a leading 0. After the day value, (you must)enter a comma followed by the year either with 2 or 4 digits.

A Date Value

We have seen that, when creating a date, you can include its value between # signs. Analternative is to provide a date as a string. To support this, the Visual Basic language provides afunction named DateValue. Its syntax is:

Public Function DateValue(ByVal StringDate As String) As DateTime

Page 350: Microsoft Visual Basic 2010 Tutorial

When calling this function, provide a valid date as argument. The validity depends on thelanguage of the operating system. If working in US English, you can use one of the formats wesaw above. Here is an example:

Public Function Main() As Integer Dim DateHired As Date

DateHired = DateValue("22-Aug-2006") MsgBox("Date Hired: " & DateHired) Return 0End Function

This would produce:

A Date as Serial

An alternative to initializing a date variable is to use a function named DateSerial. Its syntaxis:

Public Function DateSerial(ByVal [Year] As Integer, _ ByVal [Month] As Integer, _ ByVal [Day] As Integer) As DateTime

As you can see, this function allows you to specify the year, the month, and the day of a datevalue, of course without the # signs. When it has been called, this function returns a Datevalue. Here is an example:

Public Module Exercise

Public Function Main() As Integer

Dim DateHired As Date

DateHired = DateSerial(2003, 02, 08)

MsgBox("Date Hired: " & DateHired) Return 0 End Function

End Module

When passing the values to this function, you must restrict each component to the allowablerange of values. You can pass the year with two digits from 0 to 99. Here is an example:

Public Module Exercise

Public Function Main() As Integer Dim DateHired As Date

DateHired = DateSerial(03, 2, 8)

MsgBox("Date Hired: " & DateHired) Return 0 End Function

End Module

If you pass the year as a value between 0 and 99, the compiler would refer to the clock on thecomputer to get the century. At the time of this writing (in 2008), the century would be 20 andthe specified year would be added, which would produce 2003. To be more precise and reduceany confusion, you should always pass the year with 4 digits.

The month should (must) be a value between 1 and 12. If you pass a value higher than 12, thecompiler would calculate the remainder of that number by 12 (that number MOD 12 = ?). Theresult of the integer division would be used as the number of years and added to the firstargument. The remainder would be used as the month of the date value. For example, if youpass the month as 18, the integer division would produce 1, so 1 year would be added to thefirst argument. The remainder is 6 (18 MOD 12 = 6); so the month would be used as 6 (June).Here is an example:

Public Module Exercise

Public Function Main() As Integer Dim DateHired As Date

DateHired = DateSerial(2003, 18, 8) MsgBox("Date Hired: " & DateHired)

Return 0 End Function

Page 351: Microsoft Visual Basic 2010 Tutorial

End Module

This would produce:

As another example, if you pass the month as 226, the integer division (226 \ 12) produces 18and that number would be added to the first argument (2003 + 18 = 2021). The remainder of226 to 12 (226 MOD 12 = 10) is 10 and that would be used as the month. Here is an example:

Public Module Exercise

Public Function Main() As Integer Dim DateHired As Date

DateHired = DateSerial(2003, 226, 8) MsgBox("Date Hired: " & DateHired)

Return 0 End Function

End Module

This would produce:

If the month is passed as 0, it is considered 12 (December) of the previous year. If the monthis passed as -1, it is considered 11 (November) of the previous year and so on. If the month ispassed as a number lower than -11, the compiler would calculate its integer division to 12, add1 to that result, use that number as the year, calculate the remainder to 12, and use thatresult as the month.

Depending on the month, the value of the day argument can be passed as a number between 1and 28, between 1 and 29, between 1 and 30, or between 1 and 31. If the day argument ispassed as a number lower than 1 or higher than 31, the compiler uses the first day of themonth passed as the second argument. This is 1. If the day is passed as -1, the day isconsidered the last day of the previous month of the Month argument. For example, if theMonth argument is passed as 4 (April) and the Day argument is passed as -1, the compilerwould use 31 as the day because the last day of March is 31. If the Month argument is passedas 3 (March) and the Day argument is passed as -1, the compiler would refer to the Yearargument to determine whether the year is leap or not. This would allow the compiler to useeither 28 or 29 for the day value. The compiler uses this algorithm for any day value passed asthe third argument when the number is lower than 1.

If the Day argument is passed with a value higher than 28, 29, 30, or 31, the compiler usesthis same algorithm in reverse order to determine the month and the day.

Converting a Value to Date

If you have a value such as one provided as a string and you want to convert it to a date, youcan call the CDate() function. Its syntax is:

Function CDate(Value As Object) As Date

This function can take any type of value but the value must be convertible to a valid date. Ifthe function succeeds in the conversion, it produces a Date value. If the conversion fails, itproduces an error.

The Components of a Date

Introduction

As seen so far, a date is a value made of at least three parts: the year, the month, and theday. The order of these components and how they are put together to constitute a recognizable

Page 352: Microsoft Visual Basic 2010 Tutorial

date depend on the language and they are defined in the Language and Regional Settings inControl Panel.

The Year of a Date

The Visual Basic language supports the year of a date ranging from 1 to 9999. This means thatthis is the range you can consider when dealing with dates in your applications. In mostoperations, when creating a date, if you specify a value between 1 and 99, the compiler woulduse the current century for the left two digits. This means that, at the time of this writing(2008), a year such as 4 or 04 would result in the year 2004. In most cases, to be moreprecise, you should usually or always specify the year with 4 digits.

If you have a date value whose year you want to find out, you can call the Year() function. Itssyntax is:

Public Function Year(ByVal DateValue As DateTime) As Integer

As you can see, this function takes a date value as argument. The argument should hold a validdate. If it does, the function returns the numerical year of a date. Here is an example:

Public Module Exercise Public Function Main() As Integer

Dim DateHired As Date = #2/8/2004#

MsgBox("In the job since " & Year(DateHired))

Return 0 End Function

End Module

This would produce:

The Month of a Year

The month part of a date is a numeric value that goes from 1 to 12. When creating a date, youcan specify it with 1 or 2 digits. If the month is between 1 and 9 included, you can precede itwith a leading 0.

If you have a date value and want to get its month, you can call the Month() function. Itssyntax is:

Public Function Month(ByVal DateValue As DateTime) As Integer

This function takes a Date object as argument. If the date is valid, the function returns anumber between 1 and 12 for the month. Here is an example:

Public Module Exercise

Public Function Main() As Integer

Dim DateHired As Date = #2/8/2004#

MsgBox("Month hired " & Month(DateHired))

Return 0 End Function

End Module

This would produce:

As mentioned already, the Month function produces a numeric value that represents the monthof a date. Instead of getting the numeric index of the month of a date, if you want to get thename of the month, you can call a function named MonthName. Its syntax is:

Public Function MonthName(ByVal Month As Integer, _ Optional ByVal Abbreviate As Boolean = False) As String

Page 353: Microsoft Visual Basic 2010 Tutorial

This function takes one required and one optional argument. The required argument mustrepresent the value of a month. If it is valid, this function returns the corresponding name.Here is an example:

Public Module Exercise

Public Function Main() As Integer

Dim DateHired As Date = #2/8/2004#

MsgBox("Day hired " & MonthName(Month(DateHired)))

Return 0 End Function

End Module

This would produce:

The second argument allows you to specify whether you want to get the complete or the shortname. The default is the complete name, in which case the default value of the argument isFalse. If you want to get the short name, pass the second argument as True. Here is anexample:

Public Module Exercise

Public Function Main() As Integer

Dim DateHired As Date = #2/8/2004#

MsgBox("Month hired " & MonthName(Month(DateHired), True))

Return 0 End Function

End Module

The Day of a Month

The day is a numeric value in a month. Depending on the month (and the year), its value canrange from 1 to 29 (February in a leap year), from 1 to 28 (February in a non-leap year), from1 to 31 (January, March, May, July, August, October, and December), or from 1 to 30 (April,June, September, and November).

If you have a date value and you want to know its day in a year, you can call the Day()function. Its syntax is:

Public Function Day(ByVal DateValue As DateTime) As Integer

This function takes a date as argument. If the date is valid, the function returns the numericday in the month of the date argument. Here is an example:

Public Module Exercise

Public Function Main() As Integer

Dim DateHired As Date = #2/8/2004#

MsgBox("Day hired " & Day(DateHired))

Return 0 End Function

End Module

This would produce:

The Day of a Week

To get the name of the day of a week, you can a function named WeekdayName. Its syntaxis:

Page 354: Microsoft Visual Basic 2010 Tutorial

Public Function WeekdayName( _ ByVal Weekday As Integer, _ Optional ByVal Abbreviate As Boolean = False, _ Optional ByVal FirstDayOfWeekValue As FirstDayOfWeek = FirstDayOfWeek.System _) As String

This function takes one required and two optional arguments. The required argument must be,or represent, a value between 0 and 7. If you pass it as 0, the compiler will refer to theoperating system's language to determine the first day of the week, which in US English isSunday. Otherwise, if you pass one of the above indexes, the function would return thecorresponding name of the day. Here is an example:

Public Module Exercise

Public Function Main() As Integer

MsgBox("Day hired: " & WeekdayName(4))

Return 0 End Function

End Module

This would produce:

If you pass a negative value or a value higher than 7, you would receive an error.

The second argument allows you to specify whether you want to get the complete or the shortname. The default value of this argument is False, which produces a complete name. If youwant a short name, pass the second argument as True. Here is an example:

Public Module Exercise

Public Function Main() As Integer

MsgBox("Day hired: " & WeekdayName(4, True))

Return 0 End Function

End Module

As mentioned already, the Visual Basic language allows you to specify what days should be thefirst day of the week. This is the role of the third argument.

Formatting a Date Value

Introduction

Formatting a date consists of specifying how the value would be displayed to the user. TheVisual Basic language provides various options. The US English language supports two primarydate formats known as long date and short date. You can check them in the Date property pageof the Customize Regional Options accessible from the Regional Settings in Control Panel:

Page 355: Microsoft Visual Basic 2010 Tutorial

To support these primary formats, the Visual Basic language provides a function namedFormatDateTime. Its syntax is:

Function FormatDateTime( ByVal Expression As DateTime, Optional ByVal NamedFormat As DateFormat = DateFormat.GeneralDate) As String

The first argument of this function must be a valid Date value. The second argument is amember of the DateFormat enumeration. For a date, this argument can be LongDate orShortDate. Here is an example:

Public Function Main() As Integer Dim DateHired$

DateHired$ = FormatDateTime("22-Aug-2006", DateFormat.LongDate)

MsgBox("Date Hired: " & DateHired) Return 0End Function

This would produce:

Using the Format Function

To support more options, the Visual Basic language provides the Format() function that wesaw in the previous lesson. We saw that its syntax was:

Public Shared Function Format( _ ByVal Expression As Object, _ Optional ByVal Style As String = "" _) As String

Remember that the first argument is the date that needs to be formatted. The secondargument is a string that contains the formatting to apply. To create it, you use a combinationof the month, day, and/or year characters we saw as date formats. Here is an example:

Public Function Main() As Integer Dim DateHired As Date = #12/28/2006#

MsgBox("Date Hired: " & Format(DateHired, "MMMM dd, yyyy")) Return 0End Function

Page 356: Microsoft Visual Basic 2010 Tutorial

This would produce:

Built-In Time Functions

Introduction

The Visual Basic language supports time values. To create a time value, you can declare avariable of type Date. To initialize the variable, create a valid value using the rules specified inthe Regional and language Settings of Control Panel, and include that value between two #signs. Here is an example;

Public Module Exercise

Public Function Main() As Integer

Dim DepositTime As Date = #7:14#

MsgBox("Deposit Time: " & DepositTime)

Return 0 End Function

End Module

This would produce:

Creating a Time Value

Instead of including the time in # signs, you can also provide it as a string. To support this, theVisual Basic language provides a function named TimeValue. Its syntax is:

Public Function TimeValue(ByVal StringTime As String) As DateTime

This function expects a valid time as argument. If that argument is valid, the function returns atime value. Here is an example:

Public Module Exercise

Public Function Main() As Integer

Dim DepositTime As Date = TimeValue("7:14")

MsgBox("Deposit Time: " & DepositTime)

Return 0 End Function

End Module

As an alternative to initializing a time variable, you can call a function named TimeSerial. Itssyntax is:

Public Function TimeSerial(ByVal Hour As Integer, _ ByVal Minute As Integer, _ ByVal Second As Integer) As DateTime

This function allows you to specify the hour, the minute, and the second values of a time. Ifyou pass valid values, the function returns a time. Here is an example:

Public Module Exercise

Public Function Main() As Integer

Dim DepositTime As Date

DepositTime = TimeSerial(7, 14, 0)

MsgBox("Deposit Time: " & DepositTime)

Return 0 End Function

Page 357: Microsoft Visual Basic 2010 Tutorial

End Module

The Components of a Time Value

The Hours of a Day

In US English, a time is made of various parts. The first of them is the hour. The time is a 24thspatial division of a day. It is represented by a numeric value between 0 and 23. When creating atime value, you specify the hour on the left side. To get the hour of a valid time, you can call afunction named Hour. Its syntax is:

Public Function Hour(ByVal TimeValue As DateTime) As Integer

This function takes a time value as argument. If a valid time is passed, the function returns thehour part.

The Minutes of an Hour

An hour is divided in 60 parts. Each part is called a minute and is represented by a numeric valuebetween 0 and 59. If you have a time value and want to get its minute part, you can call afunction named Minute. Its syntax is:

Public Function Minute(ByVal TimeValue As DateTime) As Integer

When calling this function, pass it a time value. If the argument holds a valid value, the functionreturns a number between 0 and 59 and that represents the minutes.

The Seconds of a Minute

A minute is divided in 60 parts and each part is called a second. It is represented by a numericvalue between 0 and 59. If you have a time value and want to extract a second part from it, youcan call the Second() function named . Its syntax is:

Public Function Second(ByVal TimeValue As DateTime) As Integer

If you call this function, pass a valid time. If so, the function would return a number representsthe seconds part.

Operations on Date and Time Values

Introduction

Because dates and times are primarily considered as normal values, there are various operationsyou can perform on them. You can add or subtract a number of years or add or subtract a numberof months, etc. The Visual Basic language provides its own mechanisms for performing suchoperations thanks to its vast library of functions.

Adding a Value to a Date or a Time

To support the addition of a value to a date or a time, the Visual Basic language provides afunction named DateAdd. In the Visual Basic language, the DateAdd() function comes in twoversions whose syntaxes are:

Public Overloads Function DateAdd( _ ByVal Interval As DateInterval, _ ByVal Number As Double, _ ByVal DateValue As DateTime _) As DateTime' -or-Public Overloads Function DateAdd( _ ByVal Interval As String, _ ByVal Number As Double, _ ByVal DateValue As Object _) As DateTime

This function takes three arguments that all are required.

Because we have not studied enumerations and classes yet, we will ignore the first version.

The DateValue argument is the date or time value on which you want to perform this operation. Itmust be a valid Date or DateTime value.

The Interval argument is passed as a string. It specifies the kind of value you want to add. Thisargument will be enclosed between double quotes and can have one of the following values:

Interval Used To Add

Page 358: Microsoft Visual Basic 2010 Tutorial

s Second

n Minute

h Hour

w Numeric Weekday

ww Week of the Year

d Day

y Numeric Day of the Year

m Month

q Quarter

yyyy Year

The Number argument specifies the number of Interval units you want to add to the DateValuevalue. If you set it as positive, its value will be added. Here are examples:

Public Module Exercise

Public Function Main() As Integer Dim LoanStartDate As Date = #6/10/1998# Dim DepositTime As Date = TimeValue("7:14:00")

MsgBox("Loan Length: " & DateAdd("yyyy", 5, LoanStartDate)) MsgBox("Time Ready: " & DateAdd("h", 8, DepositTime))

Return 0 End Function

End Module

This would produce:

We saw that, to add a value to a date or a time, you could call the DateAdd() function. The firstargument of this function takes an argument that belongs to an enumeration named DateInterval.Instead of including a character or a combination of characters in double-quotes with the likelihoodof a mistake, this enumeration makes it easy by allowing you to select a member of theenumeration and use an easily recognizable name. The members of the DateInterval enumerationare:

StringInterval Enumeration Member Used To Add

s DateInterval.Second Second

n DateInterval.Minute Minute

h DateInterval.Hour Hour

w DateInterval.Weekday Numeric Weekday

ww DateInterval.WeekOfYear Week of the Year

d DateInterval.Day Day

y DateInterval.DayOfYear Numeric Day of the Year

m DateInterval.Month Month

q DateInterval.Quarter Quarter

yyyy DateInterval.Year Year

Notice that by using the DateInterval enumeration as argument, the selected interval is easier toselect. Here are examples:

Public Module Exercise

Public Function Main() As Integer

Dim LoanStartDate As Date = #6/10/1998# Dim DepositTime As Date = TimeValue("7:14:00")

Page 359: Microsoft Visual Basic 2010 Tutorial

MsgBox("Loan Length: " & DateAdd(DateInterval.Year, 5, LoanStartDate)) MsgBox("Time Ready: " & DateAdd(DateInterval.Hour, 8, DepositTime))

Return 0 End Function

End Module

Subtracting a Value From a Date or a Time

Instead of adding a value to a date or a time value, you may want to subtract. To perform thisoperation, pass the Number argument as a negative value. Here are examples:

Public Module Exercise

Public Function Main() As Integer Dim LoanPayDate As Date = #8/12/2008# Dim TimeReady As Date = TimeValue("17:05")

MsgBox("Loan Length: " & DateAdd("m", -48, LoanPayDate)) MsgBox("Time Deposited: " & DateAdd("n", -360, TimeReady))

Return 0 End Function

End Module

This would produce:

The Difference Between Two Date or Time Values

Another valuable operation performed consists of finding the difference between two date or timevalues. To help you perform this operation, the Visual Basic language provides a function namedDateDiff. This function allows you to find the number of seconds, minutes, hours, days, weeks,months, or years from two valid date or time values. The DateDiff function takes 5 arguments, 3are required and 2 are optional.

The formula of the function is

Public Overloads Function DateDiff( _ ByVal Interval As [ DateInterval | String ], _ ByVal Date1 As DateTime, _ ByVal Date2 As DateTime, _ Optional ByVal DayOfWeek As FirstDayOfWeek = FirstDayOfWeek.Sunday, _ Optional ByVal WeekOfYear As FirstWeekOfYear = FirstWeekOfYear.Jan1 _) As Long

This function takes five arguments, three of which are required and two are optional.

The Date1 argument can be the start date or start time. The Date2 argument can be the end dateor end time. These two arguments can also be reversed, in which case the Date2 argument can bethe start date or start time and the Date1 argument would be the end date or end time. Thesetwo values must be valid date or time values

The Interval argument specifies the type of value you want as a result. This argument will beenclosed between double quotes and can have one of the following values:

Interval Used To Get

s Second

n Minute

h Hour

w Numeric Weekday

ww Week of the Year

d Day

y Numeric Day of the Year

Page 360: Microsoft Visual Basic 2010 Tutorial

m Month

q Quarter

yyyy Year

Here is an example:

Public Module Exercise

Public Function Main() As Integer Dim LoanStartDate As Date = #8/12/2003# Dim LoanEndDate As Date = #10/5/2008# Dim Months As Long = DateDiff("m", LoanStartDate, LoanEndDate)

MsgBox("Loan Start Date: " & vbTab & LoanStartDate & vbCrLf & _ "Loan End Date: " & vbTab & LoanEndDate & vbCrLf & _ "Loan Length: " & vbTab & Months & " months")

Return 0 End Function

End Module

This would produce:

By default, the days of a week are counted starting on Sunday. If you want to start counting thosedays on another day, supply the Option1 argument using one of the following values: vbSunday,vbMonday, vbTuesday, vbWednesday, vbThursday, vbFriday, vbSaturday. There are othervariances to that argument.

If your calculation involves weeks or finding the number of weeks, by default, the weeks arecounted starting January 1st. If you want to count your weeks starting at a different date, use theOption2 argument to specify where the program should start.

We saw that we could use the DateDiff() function to get the difference between two date or timevalues. The first argument can be specified as a string. A better idea is to use a member of theDateInterval enumeration.

The last two arguments of this function are enumeration types. The fourth argument allows you tospecify what day should be considered the first of the week. By default, in US English, the first dayis Sunday. To change this, use a member of the FirstDayOfWeek enumeration. The membersare:

Enumeration Member ConstantValue Description

FirstDayOfWeek.System 0

The compiler will refer tothe operating system tofind out what day should bethe first. In US English, thisshould be Sunday

FirstDayOfWeek.Sunday 1 Sunday (the default in USEnglish)

FirstDayOfWeek.Monday 2 Monday

FirstDayOfWeek.Tuesday 3 Tuesday

FirstDayOfWeek.Wednesday 4 Wednesday

FirstDayOfWeek.Thursday 5 Thursday

FirstDayOfWeek.Friday 6 Friday

FirstDayOfWeek.Saturday 7 Saturday

By default, the first week of a year is the one that includes January 1st of that year. This is how itis considered in the regular date-based calculations. If you want to change this default setting, youcan use the last argument of the DateDiff() function. The value of this argument is from anenumeration named FirstWeekofYear. The members of this enumeration are:

Enumeration Member ConstantValue Description

The compiler will refer to

Page 361: Microsoft Visual Basic 2010 Tutorial

FirstWeekOfYear.System 0

the operating system tofind out what day shouldbe the first. This shouldbe the week thatincludes January 1st

FirstWeekOfYear.Jan1 1 This will be the weekthat includes January 1st

FirstWeekOfYear.FirstFourDays 2

This will be the firstweek that includes atleast the first 4 days ofthe year

FirstWeekOfYear.FirstFullWeek 3This will be the firstweek that includes thefirst 7 4 days of the year

Home Copyright © 2008-2010 FunctionX

Page 362: Microsoft Visual Basic 2010 Tutorial

Visual Basic Built-In Functions: The MessageBox

Introduction

A message box is a special dialog box used to display a piece of information to the user. The usercannot type anything in the message box. There are usually two kinds of message boxes you willcreate: one that simply displays information and one that expects the user to make a decision.

A message box is created using the MsgBox function. Its syntax is:

Public Function MsgBox( _ ByVal Prompt As Object, _ Optional ByVal Buttons As MsgBoxStyle = MsgBoxStyle.OKOnly, _ Optional ByVal Title As Object = Nothing _) As MsgBoxResult

The MsgBox() function takes three arguments and only the first one is required.

The Message of a Message Box

The Prompt argument is the string that the user will see displaying on the message box. As a string,you can display it in double quotes, like this "Your credentials have been checked.". Here is anexample:

Public Module Exercise

Public Function Main() As Integer MsgBox("Your credentials have been checked.") Return 0 End Function

End Module

This would produce:

You can also create the message from other pieces of strings. The Prompt argument can be made ofup to 1024 characters. To display the Prompt on multiple lines, you can use either the constantvbCrLf or the combination Chr(10) & Chr(13) between any two strings. Here is an example:

Public Function Main() As Integer MsgBox("Your logon credentials have been checked." & _ vbCrLf & "To complete your application, please " & _ "fill out the following survey") Return 0End Function

This would produce:

The Buttons of a Message Box

The Buttons argument specifies what button(s) should display on the message box. There aredifferent kinds of buttons available and the Visual Basic language. The Buttons options are primarymembers of an enumerations named MsgBoxStyle. The members of the MsgBoxStyle enumerationthat produce buttons are:

Button Value Alternative NumericValue Display

MsgBoxStyle.OKOnly vbOKOnly 0

MsgBoxStyle.OKCancel vbOKCancel 1

Page 363: Microsoft Visual Basic 2010 Tutorial

MsgBoxStyle.AbortRetryIgnore vbAbortRetryIgnore 2

MsgBoxStyle.YesNoCancel vbYesNoCancel 3

MsgBoxStyle.YesNo vbYesNo 4

MsgBoxStyle.RetryCancel vbRetryCancel 5

When calling the MsgBox() function and specifying the button, you can use either a member of theMsgBoxStyle enumeration or one of the above constant numeric values. Here is an example thatdisplays the Yes and the No buttons on the message box:

Public Function Main() As Integer MsgBox("Your logon credentials have been checked " & _ "and your application has been approved: Congratulations!" & _ vbCrLf & "Before leaving, would you like " & _ "to take our survey survey now?", MsgBoxStyle.YesNo) Return 0End Function

This would produce:

The Icon on a Message Box

Besides the buttons, to enhance your message box, you can display an icon in the left section of themessage box. To display an icon, you can use or add a member of the MsgBoxStyle enumeration.The members that are meant to display an icon are:

Icon Constant Alternative NumericValue Description

MsgBoxStyle.Critical vbCritical 16

MsgBoxStyle.Question vbQuestion 32

MsgBoxStyle.Exclamation vbExclamation 48

MsgBoxStyle.Information vbInformation 64

To use one of these icons, you must combine the value of the button to the desired value of the icon.To perform this combination, you use the OR operator. Here is an example:

Private Sub cmdMessageBox_Click() Dim iAnswer As Integer iAnswer = MsgBox("Your logon credentials have been checked " & _ "and your application has been approved: Congratulations!" & _ vbCrLf & "Before leaving, would you like " & _ "to take our survey survey now?", vbYesNo Or vbQuestion)End Sub

This would produce:

When calling the MsgBox() function, if you want to show one or more buttons and to show an icon,you can use either two members of the MsgBoxStyle enumeration using the OR operator, or you canadd one of the constant values of the buttons to another contant values for an icon. For example, 3+ 48 = 51 would result in displaying the buttons Yes, Ne, and Cancel, and the exclamation icon.

The Default Button of a Message Box

If you create a message box with more than one button, the most left button usually has a thickborder, indicating that it is the default. If the user presses Enter after viewing the button, the

Page 364: Microsoft Visual Basic 2010 Tutorial

effect would be the same as if he had clicked the default button. If you want, you can designateanother button as the default. To do this, you can use or add another member of theMsgBoxStyle enumeration. The members used to specify the default button are:

Default Button Constant Alternative NumericValue

If the message box containsmore than one button, thedefault would be

MsgBoxStyle.DefaultButton1 vbDefaultButton1 0 The first button

MsgBoxStyle.DefaultButton2 vbDefaultButton2 256 The second button

MsgBoxStyle.DefaultButton3 vbDefaultButton3 512 The third button

Once again, to specify a default value, use the OR operator to combine a Default Button Constantwith any other combination. Here is an example:

Public Function Main() As Integer MsgBox("Your logon credentials have been checked " & _ "and your application has been approved: Congratulations!" & _ vbCrLf & "Before leaving, would you like " & _ "to take our survey survey now?", _ MsgBoxStyle.YesNo Or _ MsgBoxStyle.Question Or MsgBoxStyle.DefaultButton2) Return 0End Function

This would produce:

These additional buttons can be used to further control what the user can do:

Constant Value Effect

MsgBoxStyle.ApplicationModal 0 The user must dismiss the message box beforeproceeding with the current database

MsgBoxStyle.SystemModal 4096 The user must dismiss this message before usingany other open application of the computer

The Title of a Message Box

The Title argument is the caption that would display on the title bar of the message box. It is astring whose word or words you can enclose between parentheses or that you can get from acreated string. The Title argument is optional. As you have seen so far, if you omit, the messagebox would display the name of the application on the title bar. Otherwise, if you want a customtitle, you can provide it as the third argument to the MsgBox() function. The caption can be asimple string. Here is an example:

Public Function Main() As Integer MsgBox("Your logon credentials have been checked " & _ "and your application has been approved: Congratulations!" & _ vbCrLf & "Before leaving, would you like " & _ "to take our survey survey now?", _ MsgBoxStyle.YesNo Or MsgBoxStyle.Question, _ "Crofton Circle of Friends - Membership Application") Return 0End Function

This would produce:

Notice that the caption is now customized instead of the name of the application. The caption canalso be a string created from an expression or emanating from a variable or value.

The Returned Value of a Message Box

The MsgBox() function can be used to return a value. This value corresponds to the button the

Page 365: Microsoft Visual Basic 2010 Tutorial

user clicked on the message box. Depending on the buttons the message box is displaying, afterthe user has clicked, the MsgBox() function can return a value. The value can be a member ofthe MsgBoxResult enumeration or a constant numeric value recognized by the Visual Basiclanguage. The value returned can be one of the following values:

If the userclick The function returns or Numeric

Value

MsgBoxResult.OK vbOK 1

MsgBoxResult.Cancel vbCancel 2

MsgBoxResult.Abort vbAbort 3

MsgBoxResult.Retry vbRetry 4

MsgBoxResult.Ignore vbIgnore 5

MsgBoxResult.Yes vbYes 6

MsgBoxResult.No vbNo 7

Home Copyright © 2008-2010 FunctionX, Inc.

Page 366: Microsoft Visual Basic 2010 Tutorial

Visual Basic Built-In Functions:Conversions

Introduction

You may recall that when studying data types, we saw that each had a corresponding functionused to convert a string value or an expression to that type. As a reminder, the general syntaxof the conversion functions is:

ReturnType = FunctionName(Expression)

The Expression could be of any kind. For example, it could be a string or expression that wouldproduce a value such as the result of a calculation. The conversion function would take such avalue, string, or expression and attempt to convert it. If the conversion is successful, the functionwould return a new value that is of the type specified by the ReturnType in our syntax.

The conversion functions are as follows:

Function

Name Return Type Description

CBool Boolean Converts an expression into a Boolean value

CByte Byte Converts an expression into Byte number

CDbl Double Converts an expression into a floating-point number withdouble precision

CDec Decimal Converts an expression into a decimal number

CInt Integer Converts an expression into an integer (natural) number

CLng Long Converts an expression into a long integer (a largenatural) number

CObj Object Converts an expression into an Object type

CSByte SByte Converts an expression into a signed byte

CShort Short Converts an expression into a short integer

CSng Single Converts an expression into a floating-point number withsingle precision

CUInt UInt Converts an expression into an unsigned integer

CULng ULong Converts an expression into an unsigned long integer

CUShort UShort Converts an expression into an unsigned short integer

Type Conversion

Conversion functions allow you to convert a known value to a another type. Besides thesefunctions, the Visual Basic language provides a function named CType. Its syntax is:

CType(expression, typename)

As you can see, the CType() function takes two arguments. The first argument is the expressionor the value that you want to convert. An example could be name of a variable or a calculation:

CType(250.48 * 14.05, ...)

The second argument is the type of value you want to convert the first argument to. From whathave learned so far, this second argument can be one of the data types we reviewed in Lesson 3.Here is an example:

CType(250.48 * 14.05, Single)

If you choose one of the Visual Basic language's data types, the expression produced by the firstargument must be able to produce a value that is conform to the type of the second argument:

The conversion from the first argument to the type of the second argument must be possible:the value produced by the first must be convertible to the second arguments. For example, ifthe first argument is a calculation, the second argument must be a number-based data type.In the same way, you cannot convert a date to a number-based type

If the first argument is a number or the result of a calculation, its resulting value must belower than or up to the range of values of the second argument. Here is an example:

Public Module Exercise

Page 367: Microsoft Visual Basic 2010 Tutorial

Public Function Main() As Integer

MsgBox(CType(250.48 * 14.05, Single))

Return 0 End Function

End Module

This would produce:

If the first argument is a number or the result of a calculation that produces an integer or afloating-point number, its resulting value must be convertible to an integer or a floating pointnumber up to the range of values of the second argument. Here is an example:

Public Module Exercise

Public Function Main() As Integer

MsgBox(CType(7942.225 * 202.46, UInteger))

Return 0 End Function

End Module

This would produce:

If the first argument is a number or the result of a calculation that produces an integer or afloating-point number, the second argument is a number-based data type but whose rangecannot hold the resulting value of the first argument, the conversion would not be allowed (theconversion will fail):

After the CType() function has performed its conversion, it returns a value that is the samecategory as the second argument. For example, you can call a CType() function that converts anexpression to a long integer. Here is an example:

Public Module Exercise

Public Function Main() As Integer Dim Number As Long

Number = CType(7942.225 * 202.46, Long)

Return 0 End Function

End Module

The function can also return a different type, as long as its type can hold the value produced bythe expression. Here are two examples:

Page 368: Microsoft Visual Basic 2010 Tutorial

Public Module Exercise

Public Function Main() As Integer Dim Number As UInteger

Number = CType(7942.225 * 202.46, Long)

Return 0 End Function

End Module

Or

Public Module Exercise

Public Function Main() As Integer Dim Number As Single

Number = CType(7942.225 * 202.46, Long)

Return 0 End Function

End Module

If you try storing the returned value into a variable that cannot hold it, you would receive anerror:

Home Copyright © 2008-2010 FunctionX, Inc.

Page 369: Microsoft Visual Basic 2010 Tutorial

Delegates

Delegates Fundamentals

Introduction

As done when you declare a variable, when you create and call a procedure, it uses a section ofmemory of the computer. This section is its address. You can access that area of memory to getto the procedure. Or, you can declare a variable that would be used to access the memory usedby the procedure.

A function pointer is a special type of variable that is used to access a function using its address.To support function pointers, the .NET Framework provides the concept of delegates. A delegate isnot a real function. It provides a syntax for a function that it would be associated with.

Creating a Delegate

Before using a delegate, you must create it or you can use one of the built-in delegates of the.NET Framework. The basic formula to create a delegate is:

[modifier] Delegate Sub/Function Name (parameter(s)) As ReturnType

The modifier factor can be Public, Private, or Friend. This is followed by either the DelegateSub or the Delegate Function expression.

A delegate must have a name: The Name factor of this formula. The name follows the rules wehave been observing for valid names of the Visual Basic language.

Because a delegate is some type of a template for a procedure, you must use parentheses. If thisprocedure will not take any argument, you can leave the parentheses empty.

If the delegate will be associated with a sub-procedure, there is no return type. Here is anexample:

Module Exercise

Delegate Sub Messenger()

End Module

If the delegate is a function-type, you must specify a ReturnType. This can be any of the datatypes we have used so far, or it can be a class.

If you create a procedure that would be associated with a delegate, you can also define it asShared.

Associating a Delegate to a Procedure

Before using a delegate, you must create a procedure it will be associated with. The proceduremust use the same syntax as the delegate:

If using a sub-procedure, both must be created as sub-procedures

If there is no argument, none of them can take an argument

Here is an example:

Module Exercise Delegate Sub Messenger()

Private Sub ShowMessage() MsgBox("Main message") End Sub

End Module

Getting the Address of a Procedure

To associate a procedure to a delegate, you must assign the address of the procedure to a variableof the delegate. This means that you must first declare a variable for the delegate.

To assist you with getting the address of a procedure, the Visual Basic language provides theAddressOf operator. To use it, type it followed by the name of the procedure that implements thedelegate. Assign that expression to the variable declared from the delegate. Here is an example:

Module Exercise

Page 370: Microsoft Visual Basic 2010 Tutorial

Delegate Sub Messenger()

Private Sub ShowMessage() MsgBox("Main message") End Sub

Public Function Main() As Integer Dim Mess As Messenger

Mess = AddressOf ShowMessage

Return 0 End Function

End Module

After assigning the address of the procedure to the delegate's variable, you can call the delegateas if it were a procedure. Here is an example:

Module Exercise Delegate Sub Messenger()

Private Sub ShowMessage() MsgBox("Main message") End Sub

Public Function Main() As Integer Dim Mess As Messenger

Mess = AddressOf ShowMessage Mess()

Return 0 End Function

End Module

In our example, we used a sub-procedure. In the same way, if necessary, you can create adelegate as a function. In this case, you would define a function to associate to that delegate.Then, you can use the same techniques we followed to associate them.

Delegates and Classes

When it comes to delegates, not only can you use a normal procedure, you can use the method ofa class to associate to a delegate. You can start by creating the class and the necessary method.Here is an example:

Module Exercise

Private Class Example Public Sub Welcome() MsgBox("A delegate with class") End Sub End Class

End Module

Of course, before using the delegate, you must declare it. This is done exactly as previously. Thedelegate must be of the same type as the method (sub-procedure or function).

Before associating the delegate to the intended method, declare a variable for it. Also declare avariable for the class. To associate the method to the delegate, get the address of the method,through its object, and assign it to the variable of the delegate. Once you have done this, you cancall the delegate's variable as if it were a procedure. Here is an example:

Module Exercise

Delegate Sub Simple()

Private Class Example Public Sub Welcome() MsgBox("A delegate with class") End Sub End Class

Public Function Main() As Integer Dim Simplicity As Simple Dim Exo As Example = New Example

Simplicity = AddressOf Exo.Welcome Simplicity()

Return 0 End Function

End Module

A delegate is actually a class. The class is named Delegate. Based on this, whenever you create adelegate, the name you give it is considered an object. That is, the name you give to the delegatebecomes an object of type Delegate. Based on the characteristics of classes, that delegate objectautomatically becomes equipped with methods.

Page 371: Microsoft Visual Basic 2010 Tutorial

Delegates and Arguments

Introduction

If you want to associate a procedure that takes arguments to a delegate, when declaring thedelegate, provide the necessary argument(s) in its parentheses. Here is an example of a delegatethat takes two arguments (and returns a value):

Module Exercise

Delegate Function Multiplication(ByVal value As Double) As Double

End Module

When defining the associated procedure, besides returning the same type of value, make sure thatthe procedure takes the same number of arguments. Here is an example:

Imports System.DrawingImports System.Windows.Forms

Module Exercise

Delegate Function Multiplication(ByVal value As Double) As Double

Public Function Area(ByVal Side As Double) As Double Return 6 * Side * Side End Function

End Module

To associate the procedure, declare a variable of the type of delegate and access the name of theprocedure using the AddressOf operator. Here is an example:

Module Exercise Delegate Function Multiplication(ByVal value As Double) As Double

Public Function Area(ByVal Side As Double) As Double Return 6 * Side * Side End Function

Public Function Main() As Integer

Dim AreaDefinition As Multiplication = New Multiplication(AddressOf Area)

Return 0 End Function

End Module

To assist you with accessing a delegate, the Delegate class is equipped with a method namedInvoke. Therefore, to associate a method to a delegate, call this method on the variable of thedelegate. The syntax of the Invoke() method is:

Public Function Invoke(method As Delegate) As Object

Here is an example:

Module Exercise Delegate Function Multiplication(ByVal value As Double) As Double

Public Function Area(ByVal Side As Double) As Double Return 6 * Side * Side End Function

Public Function Volume(ByVal Side As Double) As Double Return Side * Side * Side End Function

Public Function Main() As Integer

Dim Side As Double = 46.95 Dim AreaDefinition As Multiplication Dim VolDefinition As Multiplication

AreaDefinition = New Multiplication(AddressOf Area) VolDefinition = New Multiplication(AddressOf Volume)

MsgBox("Cube Calculation" & vbCrLf & _ "Side: " & vbTab & CStr(Side) & vbCrLf & _ "Area: " & vbTab & CStr(AreaDefinition.Invoke(Side)) & vbCrLf & _ "Volume: " & vbTab & CStr(VolDefinition.Invoke(Side)))

Return 0 End Function

End Module

A Delegate Passed as Argument

Page 372: Microsoft Visual Basic 2010 Tutorial

Using delegates, a procedure can be indirectly passed as argument to another procedure. Toproceed, first declare the necessary delegate. Here is a example of such a delegate:

Module Exercise

Delegate Function Squared(ByVal value As Double) As Double

End Module

A delegate can be passed as argument to a procedure. Such an argument would be used as if itwere a procedure itself. This means that, when accessed in the body of the procedure, the nameof the delegate must be accompanied by parentheses and if the delegate takes an argument orarguments, the argument(s) must be provided in the parentheses of the called delegate. Here is anexample:

Module Exercise Private Radius As Double Delegate Function Squared(ByVal value As Double) As Double

Public Function Area(ByVal sqd As Squared) As Double Return sqd(Radius) * Math.PI End FunctionEnd Module

After declaring a delegate, remember to define a procedure that implements the needed behaviorof that delegate. Once the procedure is ready, to associate it to a delegate, declare a variable ofthe type of the delegate using the New operator. In the parentheses of the constructor, accessthe name of the associated procedure using the AddressOf operator. To access the delegate, callthe Invoke() method. Here is an example:

Module Exercise Private Radius As Double Delegate Function Squared(ByVal value As Double) As Double

Public Function Area(ByVal sqd As Squared) As Double Return sqd(Radius) * Math.PI End Function

Public Function ValueTimesValue(ByVal value As Double) As Double Return value * value End Function

Public Function Main() As Integer

Dim Side As Double = 46.95 Dim AreaDefinition As Squared

AreaDefinition = New Squared(AddressOf ValueTimesValue)

MsgBox("Circle Calculation" & vbCrLf & _ "Side: " & vbTab & CStr(Side) & vbCrLf & _ "Area: " & vbTab & CStr(AreaDefinition.Invoke(Side)))

Return 0 End Function

End Module

Home Copyright © 2009-2010 FunctionX, Inc.

Page 373: Microsoft Visual Basic 2010 Tutorial

Namespaces

Introduction

A namespace is a section of code that is recognized with a name. A namespace allows aprogrammer or a group of programmers who work with others to create code with names thatdon't conflict with code of the other programmers or other groups.

As mentioned already, a namespace is a section of code. Therefore, it must be created in a filebefore being used.

Creating a Namespace

The formula to create a namespace is:

Namespace name End Namespace

As you can see, the creation of a namespace starts with the Namespace keyword and ends withthe End Namespace expression. On the right side of the starting Namespace keyword, enter aname. The name follows the rules we have used so far for names in the Visual Basic language.Here is an example:

Namespace Census

End Namespace

The section between the starting Namespace line and End Namespace is the body of thenamespace. In this body, you can write code as you want. For example, you can create a class init. Here is an example:

Namespace Geometry Public Class Rectangle

End ClassEnd Namespace

Of course, in the body of the class, you can write the necessary code. Here is an example:

Namespace Geometry Public Class Rectangle Public Width As Double Public Height As Double

Public Function Perimeter() As Double Return (Width + Height) * 2 End Function

Public Function Area() As Double Return Width * Height End Function End ClassEnd Namespace

Accessing Members of a Namespace

The variables, procedures, and classes created inside a namespace can be referred to as itsmembers.

To access a member of a namespace, you can use the period operator. To do this, where you wantto access the member, type the name of the namespace, followed by a period, followed by thedesired member of the namespace. Here is an example:

Namespace Geometry Public Class Rectangle End ClassEnd Namespace

Module Exercise

Public Function Main() As Integer Geometry.Rectangle

Return 0 End Function

End Module

In the same way, wherever you want to access a member of a namespace, you can simply qualifyit. Once the member has been qualified, you can use it as we saw in previous lessons. Here are

Page 374: Microsoft Visual Basic 2010 Tutorial

examples:

Namespace Geometry Public Class Rectangle Public Width As Double Public Height As Double

Public Function Perimeter() As Double Return (Width + Height) * 2 End Function

Public Function Area() As Double Return Width * Height End Function End ClassEnd Namespace

Module Exercise

Public Function Main() As Integer Dim Rect As Geometry.Rectangle Rect = New Geometry.Rectangle

Rect.Width = 40.18 Rect.Height = 28.46

MsgBox("Rectangle Characteristics" & vbCrLf & _ "Width:" & vbTab & vbTab & FormatNumber(Rect.Width) & vbCrLf & _ "Height:" & vbTab & vbTab & FormatNumber(Rect.Height) & vbCrLf & _ "Perimeter:" & vbTab & FormatNumber(Rect.Perimeter()) & vbCrLf & _ "Area:" & vbTab & vbTab & FormatNumber(Rect.Area())) Return 0 End Function

End Module

In the same way, you can create as many members as you want in the body of a namespace.

In the above code, we create our namespace in the same file that contains the Main() function.To better manage your code, you can create your namespaces in different files. Here is anexample:

Namespace Geometry Public Class Rectangle Public Width As Double Public Height As Double

Public Function Perimeter() As Double Return (Width + Height) * 2 End Function

Public Function Area() As Double Return Width * Height End Function End Class

Public Class Triangle Public Base As Double Public Height As Double

Public Function Area() As Double Return Base * Height / 2 End Function End ClassEnd Namespace

In the same way, you can create as many namespaces in as many files as you want. A namespacecan be created in more than one file.

Importing a Namespace

When accessing each member of a namespace, you can qualify its name wherever you want to useit. Here are examples that use the above namespace that was created in a separate file:

Module Exercise

Public Function Main() As Integer Dim Rect As Geometry.Rectangle = New Geometry.Rectangle

Rect.Width = 40.18 Rect.Height = 28.46

MsgBox("Rectangle Characteristics" & vbCrLf & _ "Width:" & vbTab & vbTab & FormatNumber(Rect.Width) & vbCrLf & _ "Height:" & vbTab & vbTab & FormatNumber(Rect.Height) & vbCrLf & _ "Perimeter:" & vbTab & FormatNumber(Rect.Perimeter()) & vbCrLf & _ "Area:" & vbTab & vbTab & FormatNumber(Rect.Area()))

Dim Tri As Geometry.Triangle = New Geometry.Triangle

Tri.Base = 36.09 Tri.Height = 28.46

MsgBox("Triangle Characteristics" & vbCrLf & _ "Base:" & vbTab & vbTab & FormatNumber(Tri.Base) & vbCrLf & _

Page 375: Microsoft Visual Basic 2010 Tutorial

"Height:" & vbTab & vbTab & FormatNumber(Tri.Height) & vbCrLf & _ "Area:" & vbTab & vbTab & FormatNumber(Tri.Area())) Return 0 End Function

End Module

Instead of qualifying each member, you can import the namespace in the file where you want touse it. To do this, in the top section of the file, type Imports followed by the name of thenamespace.

Nesting a Namespace

You can create one namespace inside of another namespace. This is referred to as nesting thenamespace. To nest a namespace, create its body in the body of an existing namespace. Here isan example:

Namespace Geometry

Namespace Quadrilateral End Namespace

End Namespace

Inside the new namespace, you can implement the behavior you want. For example, you cancreate a class. The parent namespace is still its own namespace and can contain any necessarything. Here is an example:

Namespace Geometry Friend Class Triangle Public Base As Double Public Height As Double

Public Function Area() As Double Return Base * Height / 2 End Function End Class

Namespace Quadrilateral Public Class Rectangle Public Width As Double Public Height As Double

Public Function Perimeter() As Double Return (Width + Height) * 2 End Function

Public Function Area() As Double Return Width * Height End Function End Class End Namespace

End Namespace

To access a member of the parent namespace, you can qualify it as we saw previously. To accessa member of the nested namespace outside the parent, type the name of the nesting namespace,followed by a period, followed by the name of the nested namespace, followed by a period, andfollowed by the member you want to access. Here are examples:

Namespace Geometry Friend Class Triangle Public Base As Double Public Height As Double

Public Function Area() As Double Return Base * Height / 2 End Function End Class

Namespace Quadrilateral Public Class Rectangle Public Width As Double Public Height As Double

Public Function Perimeter() As Double Return (Width + Height) * 2 End Function

Public Function Area() As Double Return Width * Height End Function End Class End Namespace

End Namespace

Module Exercise

Page 376: Microsoft Visual Basic 2010 Tutorial

Public Function Main() As Integer Dim Tri As Geometry.Triangle = New Geometry.Triangle

Tri.Base = 36.09 Tri.Height = 28.46

MsgBox("Triangle Characteristics" & vbCrLf & _ "Base:" & vbTab & vbTab & FormatNumber(Tri.Base) & vbCrLf & _ "Height:" & vbTab & vbTab & FormatNumber(Tri.Height) & vbCrLf & _ "Area:" & vbTab & vbTab & FormatNumber(Tri.Area()))

Dim Rect As Geometry.Quadrilateral.Rectangle

Rect = New Geometry.Quadrilateral.Rectangle Rect.Width = 40.18 Rect.Height = 28.46

MsgBox("Rectangle Characteristics" & vbCrLf & _ "Width:" & vbTab & vbTab & FormatNumber(Rect.Width) & vbCrLf & _ "Height:" & vbTab & vbTab & FormatNumber(Rect.Height) & vbCrLf & _ "Perimeter:" & vbTab & FormatNumber(Rect.Perimeter()) & vbCrLf & _ "Area:" & vbTab & vbTab & FormatNumber(Rect.Area()))

Return 0 End Function

End Module

In the same way:

You can create as many namespaces as you want inside of a nesting namespace

You can nest as many namespaces in as many nesting namespaces

Remember how to backwardly qualify the name of a member of a nested namespace. If thenamespace exists in a separate file and you want to import it, type the Imports keyword, followedby the name of the parent namespace, followed by a period, and followed by the nestednamespace. In the same way, you can import any nested namespace, as long as you appropriatelyqualify its name.

The System Namespace

To make programming in Visual Basic easier, many classes were created and stored in variousnamespaces. Each namespace is used to provide specific instructions.

One of the most regularly used namespaces in the Visual Basic language is called System. Insideof the System namespace is a class called Console. The Console class is used to display thingson the console screen also called the DOS window.

The Console class contains procedures to display information on the screen or to retrieveinformation from the user who types it in the DOS window. The procedure that is used to displaytext on the screen is called Write. To use Write(), inside of the parentheses, type the sentencebetween double-quotes. Here is an example:

Module Exercise

Public Function Main() As Integer

System.Console.Write("Welcome")

Return 0 End Function

End Module

Besides Write(), the Console class also provides a procedure called WriteLine(). Here is anexample:

Module Exercise

Public Function Main() As Integer

System.Console.WriteLine()

Return 0 End Function

End Module

The difference is that, after displaying something on the screen, the Write() method keeps thecaret on the same line but WriteLine() transfers the caret to the next line.

We mentioned that, to access a member of a namespace, you could type the name of thenamespace, followed by a period, and followed by the name of the member. This technique isreferred to as qualifying a member of a namespace. This can be long ins some cases. Instead ofqualifying a member of a namespace every time you want to use it, you can import the namespaceinto the file where you want to access its member(s). Here is an example:

Imports System

Module Exercise

Page 377: Microsoft Visual Basic 2010 Tutorial

Public Function Main() As Integer

Console.WriteLine()

Return 0 End Function

End Module

Home Copyright © 2009-2010 FunctionX, Inc.

Page 378: Microsoft Visual Basic 2010 Tutorial

Data Reading and Formatting

Data Reading

Introduction

The Console class uses Write() or WriteLine() to display values in the DOS window. Asopposed to displaying something on the screen, you may want to request a value from the user.To support this, the Console class provides the Read() method.

To use it, the name of a variable can be assigned to it. The syntax used is:

VariableName = Console.Read()

When the user types something and presses Enter, what the user had typed would be assigned tothe variable specified on the left side of the assignment operator.

Read() doesn't always have to assign its value to a variable. For example, it can be used on itsown line, which simply means that the user is expected to type something but the value typed bythe user would not be used for any significant purpose. For example, you can use the Read()function to wait for the user to press any key in order to close the DOS window.

Besides Read(), the Console class also provides ReadLine(). Like WriteLine(), after performingits assignment, ReadLine() sends the caret to the next line. Otherwise, it plays the same role asthe Read() function.

Practical Learning: Introducing Data Reading

1. Start Microsoft Visual Studio

2. Create a new Console Application named GCS1

3. In the Solution Explorer, right-click Module1 and click Rename

4. Type OrderProcessing.vb and press Enter.If asked whether you want to rename the file, click Yes

5. In the Code Editor, change the file as follows: Module OrderProcessing

Public Function Main() As Integer

Return 0 End Function

End Module

6. Save the file

String Value Request

In most assignments of your programs, you will not know the value of a string when writing yourapplication. For example, you may want the user to provide such a string. To request a string (orany of the variables we will see in this lesson), you can call the Console.Read() or theConsole.ReadLine() function and assign it to the name of the variable whose value you want toretrieve. Here is an example:

Module Module1

Sub Main() Dim FirstName As String Console.Write("Enter First Name: ") FirstName = Console.ReadLine() End Sub

End Module

Practical Learning: Reading String Values

1. To request strings from the user, change the file as follows: Module OrderProcessing

Public Function Main() As Integer Dim CustomerName As String Dim HomePhone As String

Page 379: Microsoft Visual Basic 2010 Tutorial

Console.WriteLine("-/- Georgetown Cleaning Services -/-") ' Request customer information from the user Console.Write("Enter Customer Name: ") CustomerName = Console.ReadLine() Console.Write("Enter Customer Phone: ") HomePhone = Console.ReadLine()

Console.WriteLine() ' Display the receipt Console.WriteLine("====================================") Console.WriteLine("-/- Georgetown Cleaning Services -/-") Console.WriteLine("====================================") Console.WriteLine("Customer: " + CustomerName) Console.WriteLine("Home Phone: " + HomePhone) Console.WriteLine("====================================")

Return 0 End Function

End Module

2. To execute the program, press Ctrl + F5

3. Enter the customer name as James Watson

4. Enter the phone number as (410) 493-2005This would produce: -/- Georgetown Cleaning Services -/-Enter Customer Name: James WatsonEnter Customer Phone: (410) 493-2005

====================================-/- Georgetown Cleaning Services -/-====================================Customer: James WatsonHome Phone: (410) 493-2005====================================

5. Return to your programming environment

Number Request

Everything the user types is a string. If you want to get a number from the user, first request astring. Here is an example:

Module Module1

Sub Main() Dim Number As Integer Dim strNumber As String

Console.Write("Enter a natural number: ") strNumber = Console.ReadLine() End Sub

End Module

After getting the string, you must convert it to a number. To perform this conversion, you can useone of the conversion functions we mentioned in Lesson 2 for each data type. Here is an example:

Module Module1

Sub Main() Dim Number As Integer Dim dblNumber As Integer Dim strNumber As String

Console.Write("Enter a natural number: ") strNumber = Console.ReadLine() Number = CInt(strNumber)

dblNumber = Number * 2 Console.WriteLine("Number: " + CStr(dblNumber)) End Sub

End Module

An advanced but faster way to do this is to type Console.ReadLine() in the parentheses of theconversion function. This has the same effect. Here is an example:

Module Module1

Sub Main() Dim Number As Integer Dim dblNumber As Integer

Console.Write("Enter a natural number: ") Number = CInt(Console.ReadLine())

dblNumber = Number * 2 Console.WriteLine("Number: " + CStr(dblNumber)) End Sub

End Module

Page 380: Microsoft Visual Basic 2010 Tutorial

Practical Learning: Reading Numeric Values

1. To retrieve various numbers from the user, change the file as follows: Module OrderProcessing

Public Function Main() As Integer ' Price of items Const PriceOneShirt As Double = 0.95D Const PriceAPairOfPants As Double = 2.95D Const PriceOneDress As Double = 4.55D Const TaxRate As Double = 0.0575D ' 5.75%

' Customer personal infoirmation Dim CustomerName As String Dim HomePhone As String ' Unsigned numbers to represent cleaning items Dim NumberOfShirts As Integer Dim NumberOfPants As Integer Dim NumberOfDresses As Integer ' Each of these sub totals will be used for cleaning items Dim SubTotalShirts As Double Dim SubTotalPants As Double Dim SubTotalDresses As Double ' Values used to process an order Dim TotalOrder As Double Dim TaxAmount As Double Dim SalesTotal As Double Dim AmountTended As Double Dim Difference As Double

Console.WriteLine("-/- Georgetown Cleaning Services -/-") ' Request customer information from the user Console.Write("Enter Customer Name: ") CustomerName = Console.ReadLine() Console.Write("Enter Customer Phone: ") HomePhone = Console.ReadLine()

' Request the quantity of each category of items Console.Write("Number of Shirts: ") Dim strShirts As String = Console.ReadLine() NumberOfShirts = CInt(strShirts)

Console.Write("Number of Pants: ") Dim strPants As String = Console.ReadLine() NumberOfPants = CInt(strPants)

Console.Write("Number of Dresses: ") Dim strDresses As String = Console.ReadLine() NumberOfDresses = CInt(strDresses)

' Perform the necessary calculations SubTotalShirts = NumberOfShirts * PriceOneShirt SubTotalPants = NumberOfPants * PriceAPairOfPants SubTotalDresses = NumberOfDresses * PriceOneDress ' Calculate the "temporary" total of the order TotalOrder = SubTotalShirts + SubTotalPants + SubTotalDresses

' Calculate the tax amount using a constant rate TaxAmount = TotalOrder * TaxRate ' Add the tax amount to the total order SalesTotal = TotalOrder + TaxAmount

' Communicate the total to the user... Console.Write("\nThe Total order is: ") Console.WriteLine(SalesTotal) ' and request money for the order Console.Write("Amount Tended? ") AmountTended = CDbl(Console.ReadLine())

' Calculate the difference owed to the customer ' or that the customer still owes to the store Difference = AmountTended - SalesTotal Console.WriteLine()

' Display the receipt Console.WriteLine("====================================") Console.WriteLine("-/- Georgetown Cleaning Services -/-") Console.WriteLine("====================================") Console.WriteLine("Customer: " + CustomerName) Console.WriteLine("Home Phone: " + HomePhone) Console.WriteLine("------------------------------------") Console.WriteLine("Item Type Qty Unit/Price Sub-Total") Console.WriteLine("------------------------------------") Console.Write("Shirts ") Console.Write(NumberOfShirts) Console.Write(" ") Console.Write(PriceOneShirt) Console.Write(" ") Console.WriteLine(SubTotalShirts) Console.Write("Pants ") Console.Write(NumberOfPants) Console.Write(" ") Console.Write(PriceAPairOfPants) Console.Write(" ") Console.WriteLine(SubTotalPants) Console.Write("Dresses ") Console.Write(NumberOfDresses)

Page 381: Microsoft Visual Basic 2010 Tutorial

Console.Write(" ") Console.Write(PriceOneDress) Console.Write(" ") Console.WriteLine(SubTotalDresses) Console.WriteLine("------------------------------------") Console.WriteLine("Total Order: " + CStr(TotalOrder)) Console.WriteLine("Tax Rate: " + CStr(TaxRate * 100) + "%") Console.WriteLine("Tax Amount: " + CStr(TaxAmount)) Console.WriteLine("Net Price: " + CStr(SalesTotal)) Console.WriteLine("------------------------------------") Console.WriteLine("Amount Tended: " + CStr(AmountTended)) Console.WriteLine("Difference: " + CStr(Difference)) Console.WriteLine("====================================")

Return 0 End Function

End Module

2. Execute the application

3. Enter the requested values. Here is an example of running the program: -/- Georgetown Cleaning Services -/-Enter Customer Name: Genevieve AltonEnter Customer Phone: (202) 974-8244Number of Shirts: 8Number of Pants: 2Number of Dresses: 3

The Total order is: 28.711125Amount Tended? 30

====================================-/- Georgetown Cleaning Services -/-====================================Customer: Genevieve AltonHome Phone: (202) 974-8244------------------------------------Item Type Qty Unit/Price Sub-Total------------------------------------Shirts 8 0.95 7.60Pants 2 2.95 5.90Dresses 3 4.55 13.65------------------------------------Total Order: 27.15Tax Rate: 5.7500%Tax Amount: 1.561125Net Price: 28.711125------------------------------------Amount Tended: 30Difference: 1.288875====================================

4. Return to your programming environment

Requesting Dates and Times

As done with the regular numbers, you can request a date value from the user. This is also doneby requesting a string from the user. Here is an example:

Module Module1

Sub Main() Dim strDateHired As String

strDateHired = Console.ReadLine() End Sub

End Module

After the user has entered the string you can then convert it to a Date value using CDate() as wementioned in Lesson 2.

By default, if you request only a date from the user and the user enters a valid date, the compilerwould add the midnight value to the date. If you request only the time from the user and theuser enters a valid time, the compiler would add the current date to the value. Later on, we willlearn how to isolate either only the date or only the time.

Practical Learning: Requesting Date and Time Values

1. To deal with dates and times, change the program as follows: Module OrderProcessing

Public Function Main() As Integer ' Price of items Const PriceOneShirt As Double = 0.95D Const PriceAPairOfPants As Double = 2.95D Const PriceOneDress As Double = 4.55D Const TaxRate As Double = 0.0575D ' 5.75%

' Customer personal infoirmation Dim CustomerName As String

Page 382: Microsoft Visual Basic 2010 Tutorial

Dim HomePhone As String Dim OrderDate As Date

' Unsigned numbers to represent cleaning items Dim NumberOfShirts As Integer Dim NumberOfPants As Integer Dim NumberOfDresses As Integer ' Each of these sub totals will be used for cleaning items Dim SubTotalShirts As Double Dim SubTotalPants As Double Dim SubTotalDresses As Double ' Values used to process an order Dim TotalOrder As Double Dim TaxAmount As Double Dim SalesTotal As Double Dim AmountTended As Double Dim Difference As Double

Console.WriteLine("-/- Georgetown Cleaning Services -/-") ' Request customer information from the user Console.Write("Enter Customer Name: ") CustomerName = Console.ReadLine() Console.Write("Enter Customer Phone: ") HomePhone = Console.ReadLine() Console.WriteLine( & _ "Enter the order date and time (mm/dd/yyyy hh:mm AM/PM)") OrderDate = CDate(Console.ReadLine())

' Request the quantity of each category of items Console.Write("Number of Shirts: ") Dim strShirts As String = Console.ReadLine() NumberOfShirts = CInt(strShirts)

Console.Write("Number of Pants: ") Dim strPants As String = Console.ReadLine() NumberOfPants = CInt(strPants)

Console.Write("Number of Dresses: ") Dim strDresses As String = Console.ReadLine() NumberOfDresses = CInt(strDresses)

' Perform the necessary calculations SubTotalShirts = NumberOfShirts * PriceOneShirt SubTotalPants = NumberOfPants * PriceAPairOfPants SubTotalDresses = NumberOfDresses * PriceOneDress ' Calculate the "temporary" total of the order TotalOrder = SubTotalShirts + SubTotalPants + SubTotalDresses

' Calculate the tax amount using a constant rate TaxAmount = TotalOrder * TaxRate ' Add the tax amount to the total order SalesTotal = TotalOrder + TaxAmount

' Communicate the total to the user... Console.Write("\nThe Total order is: ") Console.WriteLine(SalesTotal) ' and request money for the order Console.Write("Amount Tended? ") AmountTended = CDbl(Console.ReadLine())

' Calculate the difference owed to the customer ' or that the customer still owes to the store Difference = AmountTended - SalesTotal Console.WriteLine()

' Display the receipt Console.WriteLine("====================================") Console.WriteLine("-/- Georgetown Cleaning Services -/-") Console.WriteLine("====================================") Console.WriteLine("Customer: " + CustomerName) Console.WriteLine("Home Phone: " + HomePhone) Console.WriteLine("Date & Time: " + CStr(OrderDate)) Console.WriteLine("------------------------------------") Console.WriteLine("Item Type Qty Unit/Price Sub-Total") Console.WriteLine("------------------------------------") Console.Write("Shirts ") Console.Write(NumberOfShirts) Console.Write(" ") Console.Write(PriceOneShirt) Console.Write(" ") Console.WriteLine(SubTotalShirts) Console.Write("Pants ") Console.Write(NumberOfPants) Console.Write(" ") Console.Write(PriceAPairOfPants) Console.Write(" ") Console.WriteLine(SubTotalPants) Console.Write("Dresses ") Console.Write(NumberOfDresses) Console.Write(" ") Console.Write(PriceOneDress) Console.Write(" ") Console.WriteLine(SubTotalDresses) Console.WriteLine("------------------------------------") Console.WriteLine("Total Order: " + CStr(TotalOrder)) Console.WriteLine("Tax Rate: " + CStr(TaxRate * 100) + "%") Console.WriteLine("Tax Amount: " + CStr(TaxAmount)) Console.WriteLine("Net Price: " + CStr(SalesTotal)) Console.WriteLine("------------------------------------") Console.WriteLine("Amount Tended: " + CStr(AmountTended)) Console.WriteLine("Difference: " + CStr(Difference))

Page 383: Microsoft Visual Basic 2010 Tutorial

Console.WriteLine("====================================")

Return 0 End Function

End Module

2. Execute the project

3. Enter the requested values. Here is an example of running the program: -/- Georgetown Cleaning Services -/-Enter Customer Name: Alexander PappasEnter Customer Phone: (301) 397-9764Enter the order date and time (mm/dd/yyyy hh:mm AM/PM)06/22/98 08:26 AMNumber of Shirts: 2Number of Pants: 6Number of Dresses: 0

The Total order is: 20.727000Amount Tended? 50

====================================-/- Georgetown Cleaning Services -/-====================================Customer: Alexander PappasHome Phone: (301) 397-9764Date & Time: 6/22/1998 8:26:00 AM------------------------------------Item Type Qty Unit/Price Sub-Total------------------------------------Shirts 2 0.95 1.90Pants 6 2.95 17.70Dresses 0 4.55 0------------------------------------Total Order: 19.60Tax Rate: 5.7500%Tax Amount: 1.127000Net Price: 20.727000------------------------------------Amount Tended: 50Difference: 29.273000====================================

4. Return to your programming environment

Formatting Data Display

Introduction

Instead of using two Write() or a combination of Write() and WriteLine() to display data, youcan convert a value to a string and display it directly. To do this, you can provide two strings tothe Write() or WriteLine() and separate them with a comma:

1. The first part of the string provided to Write() or WriteLine() is the complete string thatwould display to the user. This first string itself can be made of different sections:

a. One section is a string in any way you want it to display

b. Another section is a number included between an opening curly bracket "{" and a closingcurly bracket "}". This combination of "{" and "}" is referred to as a placeholder

You can put the placeholder anywhere inside of the string. The first placeholder musthave number 0. The second must have number 1, etc. With this technique, you cancreate the string anyway you like and use the placeholders anywhere inside of the string

2. The second part of the string provided to Write() or WriteLine() is the value that you wantto display. It can be one value if you used only one placeholder with 0 in the first string. Ifyou used different placeholders, you can then provide a different value for each one of them inthis second part, separating the values with a comma

Here are examples:

Module Module1

Sub Main() Dim FullName As String = "Anselme Bogos" Dim Age As Integer = 15 Dim HSalary As Double = 22.74

Console.WriteLine("Full Name: {0}", FullName) Console.WriteLine("Age: {0}", Age) Console.WriteLine("Distance: {0}", HSalary) End Sub

End Module

This would produce:

Page 384: Microsoft Visual Basic 2010 Tutorial

Full Name: Anselme BogosAge: 15Distance: 22.74

As mentioned already, the numeric value typed in the curly brackets of the first part is an orderednumber. If you want to display more than one value, provide each incremental value in its curlybrackets. The syntax used is:

Write("To Display {0} {1} {2} {n}", First, Second, Third, nth)

You can use the sections between a closing curly bracket and an opening curly bracket to create ameaningful sentence.

Practical Learning: Displaying Data With Placeholders

1. To use curly brackets to display data, change the file as follows: Module OrderProcessing

Public Function Main() As Integer ' Price of items Const PriceOneShirt As Double = 0.95D Const PriceAPairOfPants As Double = 2.95D Const PriceOneDress As Double = 4.55D Const TaxRate As Double = 0.0575D ' 5.75%

' Customer personal infoirmation Dim CustomerName As String Dim HomePhone As String Dim OrderDate As Date

' Unsigned numbers to represent cleaning items Dim NumberOfShirts As Integer Dim NumberOfPants As Integer Dim NumberOfDresses As Integer ' Each of these sub totals will be used for cleaning items Dim SubTotalShirts As Double Dim SubTotalPants As Double Dim SubTotalDresses As Double ' Values used to process an order Dim TotalOrder As Double Dim TaxAmount As Double Dim SalesTotal As Double Dim AmountTended As Double Dim Difference As Double

Console.WriteLine("-/- Georgetown Cleaning Services -/-") ' Request customer information from the user Console.Write("Enter Customer Name: ") CustomerName = Console.ReadLine() Console.Write("Enter Customer Phone: ") HomePhone = Console.ReadLine() Console.WriteLine("Enter the order date and time " & _ "(mm/dd/yyyy hh:mm AM/PM)") OrderDate = CDate(Console.ReadLine())

' Request the quantity of each category of items Console.Write("Number of Shirts: ") Dim strShirts As String = Console.ReadLine() NumberOfShirts = CInt(strShirts)

Console.Write("Number of Pants: ") Dim strPants As String = Console.ReadLine() NumberOfPants = CInt(strPants)

Console.Write("Number of Dresses: ") Dim strDresses As String = Console.ReadLine() NumberOfDresses = CInt(strDresses)

' Perform the necessary calculations SubTotalShirts = NumberOfShirts * PriceOneShirt SubTotalPants = NumberOfPants * PriceAPairOfPants SubTotalDresses = NumberOfDresses * PriceOneDress ' Calculate the "temporary" total of the order TotalOrder = SubTotalShirts + SubTotalPants + SubTotalDresses

' Calculate the tax amount using a constant rate TaxAmount = TotalOrder * TaxRate ' Add the tax amount to the total order SalesTotal = TotalOrder + TaxAmount

' Communicate the total to the user... Console.Write("\nThe Total order is: ") Console.WriteLine(SalesTotal) ' and request money for the order Console.Write("Amount Tended? ") AmountTended = CDbl(Console.ReadLine())

' Calculate the difference owed to the customer ' or that the customer still owes to the store Difference = AmountTended - SalesTotal Console.WriteLine()

' Display the receipt Console.WriteLine("====================================") Console.WriteLine("-/- Georgetown Cleaning Services -/-") Console.WriteLine("====================================")

Page 385: Microsoft Visual Basic 2010 Tutorial

Console.WriteLine("Customer: {0}", CustomerName) Console.WriteLine("Home Phone: {0}", HomePhone) Console.WriteLine("Date & Time: {0}", OrderDate) Console.WriteLine("------------------------------------") Console.WriteLine("Item Type Qty Unit/Price Sub-Total") Console.WriteLine("------------------------------------") Console.WriteLine("Shirts {0} {1} {2}", _ NumberOfShirts, PriceOneShirt, SubTotalShirts) Console.WriteLine("Pants {0} {1} {2}", _ NumberOfPants, PriceAPairOfPants, SubTotalPants) Console.WriteLine("Dresses {0} {1} {2}", _ NumberOfDresses, PriceOneDress, SubTotalDresses) Console.WriteLine("------------------------------------") Console.WriteLine("Total Order: {0}", TotalOrder) Console.WriteLine("Tax Rate: {0}%", TaxRate * 100) Console.WriteLine("Tax Amount: {0}", TaxAmount) Console.WriteLine("Net Price: {0}", SalesTotal) Console.WriteLine("------------------------------------") Console.WriteLine("Amount Tended: {0}", AmountTended) Console.WriteLine("Difference: {0}", Difference) Console.WriteLine("====================================")

Return 0 End Function

End Module

2. Execute the program

3. Enter the requested values as done previously

4. Return to your programming environment

Conversion To String

We mentioned earlier that everything the user types using the keyboard is primarily a string andit's your job to convert it to the appropriate type. In reverse, if you have a value that is not astring, you can easily convert it to a string. To support this, we saw in the previous lesson thateach data type is equipped with ToString.

To convert value of a primitive data type to a string, type the name of the variable, followed by aperiod, followed, followed by ToString(). Here is an example:

Module Module1

Sub Main() Dim FullName As String = "Anselme Bogos" Dim Age As Integer = 15 Dim HSalary As Double = 22.74

Console.WriteLine("Full Name: {0}", FullName) Console.WriteLine("Age: {0}", Age.ToString()) Console.WriteLine("Distance: {0}", HSalary.ToString()) End Sub

End Module

In some cases, you will type something in the parentheses of ToString().

Number Formatting

To properly display data in a friendly and most familiar way, you can format it. Formatting tells thecompiler what kind of data you are using and how you want the compiler to display it to the user.As it happens, you can display a natural number in a common value or, depending on thecircumstance, you may prefer to show it as a hexadecimal value. When it comes to double-precision numbers, you may want to display a distance with three values on the right side of thedecimal separator and in some cases, you may want to display a salary with only 2 decimalplaces.

The System namespace provides a specific letter that you can use in the Write() orWriteLine()'s placeholder for each category of data to display. To format a value, in theplaceholder of the variable or value, after the number, type a colon and one of the appropriateletter from the following table. If you are using ToString(), then, in the parentheses ofToString(), you can include a specific letter or combination inside of double-quotes. The lettersand their meanings are:

Character Used For

c C Currency values

d D Decimal numbers

e E Scientific numeric display such as 1.45e5

f F Fixed decimal numbers

g G General and most common type ofnumbers

n N Natural numbers

Page 386: Microsoft Visual Basic 2010 Tutorial

r R Roundtrip formatting

x X Hexadecimal formatting

p P Percentages

Here are examples:

Module Module1

Sub Main() Dim Distance As Double = 248.38782 Dim Age As Integer = 15 Dim NewColor As Integer = 3478 Dim HourlySalary As Double = 22.74 Dim HoursWorked As Double = 35.5018473 Dim WeeklySalary As Double = HourlySalary * HoursWorked

Console.WriteLine("Distance: {0}", Distance.ToString("E")) Console.WriteLine("Age: {0}", Age.ToString()) Console.WriteLine("Color: {0}", NewColor.ToString("X")) Console.WriteLine("Weekly Salary: {0} for {1} hours", _ WeeklySalary.ToString("c"), HoursWorked.ToString("F")) End Sub

End Module

This would produce:

Distance: 2.483878E+002Age: 15Color: D96Weekly Salary: $807.31 for 35.50 hours

As you may have noticed, if you leave the parentheses of ToString() empty, the compiler woulduse a default formatting to display the value.

As opposed to calling ToString(), you can use the above letters in the curly brackets of the firstpart of Write() or WriteLine(). In this case, after the number in the curly brackets, type thecolon operator followed by the letter.

Practical Learning: Formatting Data Display

1. To format data display, change the file as follows: Module OrderProcessing

Public Function Main() As Integer ' Price of items Const PriceOneShirt As Double = 0.95D Const PriceAPairOfPants As Double = 2.95D Const PriceOneDress As Double = 4.55D Const TaxRate As Double = 0.0575D ' 5.75%

' Customer personal infoirmation Dim CustomerName As String Dim HomePhone As String Dim OrderDate As Date

' Unsigned numbers to represent cleaning items Dim NumberOfShirts As Integer Dim NumberOfPants As Integer Dim NumberOfDresses As Integer ' Each of these sub totals will be used for cleaning items Dim SubTotalShirts As Double Dim SubTotalPants As Double Dim SubTotalDresses As Double ' Values used to process an order Dim TotalOrder As Double Dim TaxAmount As Double Dim SalesTotal As Double Dim AmountTended As Double Dim Difference As Double

Console.WriteLine("-/- Georgetown Cleaning Services -/-") ' Request customer information from the user Console.Write("Enter Customer Name: ") CustomerName = Console.ReadLine() Console.Write("Enter Customer Phone: ") HomePhone = Console.ReadLine() Console.WriteLine("Enter the order date and time " & _ "(mm/dd/yyyy hh:mm AM/PM)") OrderDate = CDate(Console.ReadLine()) ' Request the quantity of each category of items Console.Write("Number of Shirts: ") Dim strShirts As String = Console.ReadLine() NumberOfShirts = CInt(strShirts) Console.Write("Number of Pants: ") Dim strPants As String = Console.ReadLine() NumberOfPants = CInt(strPants) Console.Write("Number of Dresses: ") Dim strDresses As String = Console.ReadLine() NumberOfDresses = CInt(strDresses)

Page 387: Microsoft Visual Basic 2010 Tutorial

' Perform the necessary calculations SubTotalShirts = NumberOfShirts * PriceOneShirt SubTotalPants = NumberOfPants * PriceAPairOfPants SubTotalDresses = NumberOfDresses * PriceOneDress ' Calculate the "temporary" total of the order TotalOrder = SubTotalShirts + SubTotalPants + SubTotalDresses

' Calculate the tax amount using a constant rate TaxAmount = TotalOrder * TaxRate ' Add the tax amount to the total order SalesTotal = TotalOrder + TaxAmount

' Communicate the total to the user... Console.Write("\nThe Total order is: ") Console.WriteLine(SalesTotal) ' and request money for the order Console.Write("Amount Tended? ") AmountTended = CDbl(Console.ReadLine())

' Calculate the difference owed to the customer ' or that the customer still owes to the store Difference = AmountTended - SalesTotal Console.WriteLine()

' Display the receipt Console.WriteLine("====================================") Console.WriteLine("-/- Georgetown Cleaning Services -/-") Console.WriteLine("====================================") Console.WriteLine("Customer: {0}", CustomerName) Console.WriteLine("Home Phone: {0}", HomePhone) Console.WriteLine("Date & Time: {0}", OrderDate) Console.WriteLine("------------------------------------") Console.WriteLine("Item Type Qty Unit/Price Sub-Total") Console.WriteLine("------------------------------------") Console.WriteLine("Shirts {0} {1:C} {2}", _ NumberOfShirts, PriceOneShirt, SubTotalShirts.ToString("C")) Console.WriteLine("Pants {0} {1} {2:C}", _ NumberOfPants, PriceAPairOfPants.ToString("C"), SubTotalPants) Console.WriteLine("Dresses {0} {1:C} {2:C}", _ NumberOfDresses, PriceOneDress, SubTotalDresses) Console.WriteLine("------------------------------------") Console.WriteLine("Total Order: {0:C}", TotalOrder) Console.WriteLine("Tax Rate: {0:P}", TaxRate) Console.WriteLine("Tax Amount: {0}", TaxAmount.ToString("C")) Console.WriteLine("Net Price: {0:F}", SalesTotal) Console.WriteLine("------------------------------------") Console.WriteLine("Amount Tended: {0:C}", AmountTended) Console.WriteLine("Difference: {0:C}", Difference) Console.WriteLine("====================================")

Return 0 End Function

End Module

2. Save it and switch to the Command Prompt. Then compile the file and execute the application.Here is an example: -/- Georgetown Cleaning Services -/-Enter Customer Name: Gretchen McCormackEnter Customer Phone: (410) 739-2884Enter the order date and time (mm/dd/yyyy hh:mm AM/PM)04/09/2001 10:25 AMNumber of Shirts: 5Number of Pants: 12Number of Dresses: 8

The Total order is: 80.951625Amount Tended? 100

====================================-/- Georgetown Cleaning Services -/-====================================Customer: Gretchen McCormackHome Phone: (410) 739-2884Date & Time: 4/9/2001 10:25:00 AM------------------------------------Item Type Qty Unit/Price Sub-Total------------------------------------Shirts 5 $0.95 $4.75Pants 12 $2.95 $35.40Dresses 8 $4.55 $36.40------------------------------------Total Order: $76.55Tax Rate: 5.75 %Tax Amount: $4.40Net Price: 80.95------------------------------------Amount Tended: $100.00Difference: $19.05====================================

3. Return to your programming environment

Line Formatting

Page 388: Microsoft Visual Basic 2010 Tutorial

In the above programs, to display a line of text, we easily used Write() or WriteLine(). Toposition text of different lengths one above the other, we had to "corrupt" a string by includingextra-empty spaces. Such a technique is uncertain and less professional. Fortunately, you canhighly format how a string or a line of text should display. The .NET Framework providesmechanisms to control the amount of space used to display a string of text and how to align thatstring on its line.

To specify the amount of space used to display a string, you can use its placeholder in Write() orWriteLine(). To do this, in the placeholder, type the 0 or the incrementing number of the placerand its formatting character if necessary and if any. Then, type a comma followed by the numberof characters equivalent to the desired width. Here are examples:

Module Module1

Sub Main() Dim FullName As String = "Anselme Bogos" Dim Age As Integer = 15 Dim HourlySalary As Double = 22.74

Console.WriteLine("Full Name: {0,20}", FullName) Console.WriteLine("Age:{0,14}", Age.ToString()) Console.WriteLine("Distance: {0:C,8}", HourlySalary.ToString()) End Sub

End Module

This would produce:

Full Name: Anselme BogosAge: 15Distance: 22.74

The sign you provide for the width is very important. If it is positive, the line of text is aligned tothe right. This should be your preferred alignment for numeric values. If the number is negative,then the text is aligned to the left.

Data and Time Formatting

As mentioned earlier, when the user enters a date value for a DateTime variable, the compileradds a time part to the value. Fortunately, if you want to consider only the date or only the timepart, you can specify this to the compiler. To support this, the DateTime data type provides aseries of letters you can use to format how its value should be displayed to the user. Thecharacter is entered in the placeholder of the DateTime variable after the 0 or the incrementalnumeric value.

Practical Learning: Controlling Date/Time Formatting

1. To control formatting of date and time, change the file as follows: Module OrderProcessing

Public Function Main() As Integer ' Price of items Const PriceOneShirt As Double = 0.95D Const PriceAPairOfPants As Double = 2.95D Const PriceOneDress As Double = 4.55D Const TaxRate As Double = 0.0575D ' 5.75%

' Customer personal infoirmation Dim CustomerName As String Dim HomePhone As String Dim OrderDate As Date Dim OrderTime As Date

' Unsigned numbers to represent cleaning items Dim NumberOfShirts As Integer Dim NumberOfPants As Integer Dim NumberOfDresses As Integer ' Each of these sub totals will be used for cleaning items Dim SubTotalShirts As Double Dim SubTotalPants As Double Dim SubTotalDresses As Double ' Values used to process an order Dim TotalOrder As Double Dim TaxAmount As Double Dim SalesTotal As Double Dim AmountTended As Double Dim Difference As Double

Console.WriteLine("-/- Georgetown Cleaning Services -/-") ' Request customer information from the user Console.Write("Enter Customer Name: ") CustomerName = Console.ReadLine() Console.Write("Enter Customer Phone: ") HomePhone = Console.ReadLine() Console.Write("Enter the order date(mm/dd/yyyy): ") OrderDate = CDate(Console.ReadLine()) Console.Write("Enter the order time(hh:mm AM/PM): ") OrderTime = CDate(Console.ReadLine()) ' Request the quantity of each category of items

Page 389: Microsoft Visual Basic 2010 Tutorial

Console.Write("Number of Shirts: ") Dim strShirts As String = Console.ReadLine() NumberOfShirts = CInt(strShirts) Console.Write("Number of Pants: ") Dim strPants As String = Console.ReadLine() NumberOfPants = CInt(strPants) Console.Write("Number of Dresses: ") Dim strDresses As String = Console.ReadLine() NumberOfDresses = CInt(strDresses) ' Perform the necessary calculations SubTotalShirts = NumberOfShirts * PriceOneShirt SubTotalPants = NumberOfPants * PriceAPairOfPants SubTotalDresses = NumberOfDresses * PriceOneDress ' Calculate the "temporary" total of the order TotalOrder = SubTotalShirts + SubTotalPants + SubTotalDresses

' Calculate the tax amount using a constant rate TaxAmount = TotalOrder * TaxRate ' Add the tax amount to the total order SalesTotal = TotalOrder + TaxAmount

' Communicate the total to the user... Console.Write("\nThe Total order is: ") Console.WriteLine(SalesTotal) ' and request money for the order Console.Write("Amount Tended? ") AmountTended = CDbl(Console.ReadLine())

' Calculate the difference owed to the customer ' or that the customer still owes to the store Difference = AmountTended - SalesTotal Console.WriteLine()

' Display the receipt Console.WriteLine("====================================") Console.WriteLine("-/- Georgetown Cleaning Services -/-") Console.WriteLine("====================================") Console.WriteLine("Customer: {0}", CustomerName) Console.WriteLine("Home Phone: {0}", HomePhone) Console.WriteLine("Order Date: {0:D}", OrderDate) Console.WriteLine("Order Time: {0:t}", OrderTime) Console.WriteLine("------------------------------------") Console.WriteLine("Item Type Qty Unit/Price Sub-Total") Console.WriteLine("------------------------------------") Console.WriteLine("Shirts {0} {1:C} {2}", _ NumberOfShirts, PriceOneShirt, SubTotalShirts.ToString("C")) Console.WriteLine("Pants {0} {1} {2}", _ NumberOfPants, PriceAPairOfPants, SubTotalPants) Console.WriteLine("Dresses {0} {1:C} {2:C}", _ NumberOfDresses, PriceOneDress, SubTotalDresses) Console.WriteLine("------------------------------------") Console.WriteLine("Total Order: {0:C}", TotalOrder) Console.WriteLine("Tax Rate: {0:P}", TaxRate) Console.WriteLine("Tax Amount: {0}", TaxAmount.ToString("C")) Console.WriteLine("Net Price: {0:F}", SalesTotal) Console.WriteLine("------------------------------------") Console.WriteLine("Amount Tended: {0:C}", AmountTended) Console.WriteLine("Difference: {0:C}", Difference) Console.WriteLine("====================================")

Return 0 End Function

End Module

2. Save, compile, and run the program. Here is an example: -/- Georgetown Cleaning Services -/-Enter Customer Name: Antoinette CalhounEnter Customer Phone: (703) 797-1135Enter the order date(mm/dd/yyyy): 04/12/2002Enter the order time(hh:mm AM/PM): 2:12 PMNumber of Shirts: 5Number of Pants: 2Number of Dresses: 1

The Total order is: $16.07Amount Tended? 20

====================================-/- Georgetown Cleaning Services -/-====================================Customer: Antoinette CalhounHome Phone: (703) 797-1135Order Date: Friday, April 12, 2002Order Time: 2:12 PM------------------------------------Item Type Qty Unit/Price Sub-Total------------------------------------Shirts 5 $0.95 $4.75Pants 2 $2.95 $5.90Dresses 1 $4.55 $4.55------------------------------------Total Order: $15.20Tax Rate: 5.75 %Tax Amount: $0.87

Page 390: Microsoft Visual Basic 2010 Tutorial

Net Price: $16.07------------------------------------Amount Tended: $20.00Difference: $3.93====================================

3. Return to your programming environment

Previous Copyright © 2009-2010 FunctionX, Inc. Next

Page 391: Microsoft Visual Basic 2010 Tutorial

Custom Libraries

Introduction

If you cannot find a function you want, you can create one and be able to use it. If you plan touse such a function over and over again in different programs, you can create a library and storethe function in it. You can even create one or a series of commercial functions and be able todistribute or sell it through a library.

A library is a program that contains procedures and/or other resources that other programs canuse. Such a program is created with the same approach as the programs we have created so far.Because a library is not an executable, it does not need the Main() procedure. A library usuallyhas the extension .dll.

Creating a Library

A library can be made of a single file or as many files as necessary. A file that is part of a librarycan contain one or more procedures (or classes). Each procedure (or class) should implement abehavior that can eventually be useful and accessible to other procedures (or classes). Thecontents of a library are created exactly like those we have used so far. Everything depends onhow you compile it.

To create a library:

On the main menu of Microsoft Visual Studio, you can click File -> New -> Project

On the Start Page, on the right side of Create, you can click Project

On the Standard toolbar, you can click the New Project button or click the arrow of the NewProject button and click New Project

In the Templates list of the New Project dialog box, click Class Library. Accept or specify the nameand click OK. Once the starting project has been generated, write the necessary code. To compileit, on the main menu, click Build -> Build Solution. If you were working from the commandprompt, you would execute the following command:

vbc /target:library NameOfFile.vb

After doing this, a library with the name of the file and the extension .dll would be created. If youuse the above technique, the new library would be created using the name of the file. If you areworking from the Command Prompt, to compile the project and create a custom name, use thefollowing syntax:

vbc /target:library /out:DesiredNameOfLibrary.dll NameOfFile.vb

Here is an example:

vbc /target:library /out:Arithmetic.dll exo.vb

Practical Learning: Creating a Library

1. Start Microsoft Visual Studio

2. To start a new project, on the main menu, click File -> New -> Project...

3. In the Project Types list, make sure Visual Basic is selected.In the Templates List, click Class Library

4. Change the Name to Arithmetic and click OK

5. In the Solution Explorer, right-click Module.vb and click Rename

6. Type Operations.vb and press Enter

7. Change the file as follows:

Public Class Arithmetic Function Add(ByVal x As Double, ByVal y As Double) As Double Return x + y End Function

Function Subtract(ByVal x As Double, ByVal y As Double) As Double Return x - y End Function

Function Multiply(ByVal x As Double, ByVal y As Double) As Double Return x * y End Function

Page 392: Microsoft Visual Basic 2010 Tutorial

Function Divide(ByVal x As Double, ByVal y As Double) As Double If y = 0 Then Return 0 Return x / y End FunctionEnd Class

8. To create the library, on the main menu, click Build -> Build Arithmetic

9. To start another project, on the main menu, click File -> New -> Project...

10. In the Templates List, click Console Application

11. Change the Name to Algebra and click OK

12. In Windows Explorer or My Documents, locate the Arithmetic folder that contains the libraryproject. Access a sub-folder of the same name, followed by the bin sub-folder, and followed bythe Debug sub-folder

13. Right-click Arithmetic.dll and click Copy

14. Still in Windows Explorer or My Documents, locate the Algebra folder that contains the currentproject. Right-click the sub-folder of the same name and click Paste

15. In the Solution Explorer, right-click Algebra and click Add Reference...

16. In the Add Reference dialog box, click the Browse tab

17. Use the Look In combo box to locate and select a sub-folder named Algebra in the currentproject

18. Click Arithmetic.dll and click OK

19. In the Solution Explorer, right-click Module1.vb and click Rename

20. Type Exercise.vb and press Enter. Accept to make all necessary changes

21. Change the the file as follows:

Imports Operations

Module Exercise

Public Function Main() As Integer Dim Result As Double Dim Oper As Arithmetic Dim Number1 As Double, Number2 As Double

Number1 = 244.58 Number2 = 5082.88 Oper = New Arithmetic Result = Oper.Add(Number1, Number2)

MsgBox(Number1 & " + " & Number2 & " = " & Result) Return 0 End Function

End Module

22. To execute the project, on the main menu, click Debug -> Start Without Debugging

Home Copyright © 2009-2010 FunctionX, Inc.

Page 393: Microsoft Visual Basic 2010 Tutorial

Error Handling

Introduction to Errors

Overview

We always want to create a problem-free application, one that always behaves as expected. Inreality, many things can go wrong while a program is running. As an application developer, youshould predict as many bad behaviors as possible so you can take appropriate actions. To assistyou with dealing with errors, the Visual Basic language provides many keywords, operators, andtechniques.

Introduction to Handling Errors

To deal with errors in your code, the Visual Basic language provides various techniques. One wayyou can do this is to prepare your code for errors. When an error occurs, you would present amessage to the user to make him/her aware of the issue (the error).

To prepare a message, you can create a section of code in the procedure where the error wouldoccur. To start that section, you create a label. Here is an example:

Module Exercise

Public Function Main() As Integer

ThereWasAProblem:

Return 0 End Function

End Module

Notice that the section starts with a label. After (under) the label, you can specify your message.You can formulate the message using Console.WriteLine() or a message box. Here is anexample:

Module Exercise

Public Function Main() As Integer

ThereWasAProblem: Console.WriteLine("An error occurred when the application executed") Return 0 End Function

End Module

If you simply create a label and its message like this, its section would always execute. Here is anexample:

Module Exercise

Public Function Main() As Integer Dim HourlySalary As Double Dim WeeklySalary As Double

' The following line may produce an error, such as ' if the user types an invalid number HourlySalary = CDbl(InputBox("Enter the employee's hourly salary:"))

' If there was an error, the flow would jump to the label WeeklySalary = HourlySalary * 40

Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary)) Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary))

ThereWasAProblem: Console.WriteLine("An error occurred when the application executed") Return 0 End Function

End Module

Here is an example of running the program:

Hourly Salary: 22.50Weekly Salary: 900.00An error occurred when the application executedPress any key to continue . . .

To avoid this, you should find a way to interrupt the flow of the program before the label section.One way you can do this is to add a line marked Exit Sub before the label. This would be done as

Page 394: Microsoft Visual Basic 2010 Tutorial

follows:

Module Exercise

Public Function Main() As Integer Dim HourlySalary As Double Dim WeeklySalary As Double

' The following line may produce an error, such as ' if the user types an invalid number HourlySalary = CDbl(InputBox("Enter the employee's hourly salary:"))

' If there was an error, the flow would jump to the label WeeklySalary = HourlySalary * 40

Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary)) Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary))

Exit Function

ThereWasAProblem: Console.WriteLine("An error occurred when the application executed") Return 0 End Function

End Module

Here is an example of running the program:

Hourly Salary: 15.85Weekly Salary: 634.00Press any key to continue . . .

In Case of Error

Jump to a Label

We saw that you can create a label that would present a message to the user when a problemhappens. Before an error occurs, you would indicate to the compiler where to go if an error occurs.To provide this information, under the line that starts the procedure, type an On Error GoToexpression followed by the name of the label where you created the message. Here is an example:

Module Exercise

Public Function Main() As Integer On Error GoTo ThereWasAProblem

Dim HourlySalary As Double Dim WeeklySalary As Double

' The following line may produce an error, such as ' if the user types an invalid number HourlySalary = CDbl(InputBox("Enter the employee's hourly salary:"))

' If there was an error, the flow would jump to the label WeeklySalary = HourlySalary * 40

Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary)) Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary))

Exit Function

ThereWasAProblem: Console.WriteLine("An error occurred when the application executed") Return 0 End Function

End Module

The On Error GoTo indicates to the compiler where to transfer code if an error occurs. Here is anexample of running the program:

An error occurred when the application executedPress any key to continue . . .

Go to a Numbered Label

Instead of defining a lettered label where to jump in case of error, you can create a numeric label:

Module Exercise

Page 395: Microsoft Visual Basic 2010 Tutorial

Public Function Main() As Integer Dim HourlySalary As Double Dim WeeklySalary As Double

' The following line may produce an error, such as ' if the user types an invalid number HourlySalary = CDbl(InputBox("Enter the employee's hourly salary:"))

' If there was an error, the flow would jump to the label WeeklySalary = HourlySalary * 40

Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary)) Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary))

Exit Function

28: Console.WriteLine("An error occurred when the application executed") Return 0 End Function

End Module

After creating the numeric label, you can ask the compiler to jump to it if a problem occurs. To dothis, type On Error GoTo followed by the numeric label. The compiler would still jump to it whenappropriate. Here is an example:

Module Exercise

Public Function Main() As Integer On Error GoTo 28

Dim HourlySalary As Double Dim WeeklySalary As Double

' The following line may produce an error, such as ' if the user types an invalid number HourlySalary = CDbl(InputBox("Enter the employee's hourly salary:"))

' If there was an error, the flow would jump to the label WeeklySalary = HourlySalary * 40

Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary)) Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary))

Exit Function

28: Console.WriteLine("An error occurred when the application executed") Return 0 End Function

End Module

This version of the program would behave like the previous one and produce the same result.

Notice that the numeric label works like the lettered label. In other words, before writing the OnError GoTo expression, you must have created the label. In reality, this is not a rule. You can askthe compiler to let you deal with the error one way or another. To do this, use the On Error GoTo0 or On Error GoTo -1 expression. Here is an example:

Module Exercise

Public Function Main() As Integer On Error GoTo 0

Dim HourlySalary As Double Dim WeeklySalary As Double

' The following line may produce an error, such as ' if the user types an invalid number HourlySalary = CDbl(InputBox("Enter the employee's hourly salary:"))

' If there was an error, the flow would jump to the label WeeklySalary = HourlySalary * 40

Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary)) Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary))

Return 0 End Function

End Module

In this case, if/when the error occurs, you must have a way to deal with it.

Resume the Code Flow

In every code we have explored so far, we anticipated that there could be a problem and we dealtwith it. In most cases, after dealing with the error, you must find a way to continue with a normalflow of your program. In some other cases, you may even want to ignore the error and proceed asif everything were normal, or you don't want to bother the user with some details of the error.

After programmatically dealing with an error, to resume with the normal flow of the program, you

Page 396: Microsoft Visual Basic 2010 Tutorial

use the Resume operator. It presents many options.

After an error has occurred, to ask the compiler to proceed with the regular flow of the program,type the Resume keyword. Here is an example:

Module Exercise

Public Function Main() As Integer On Error GoTo ThereWasAProblem

Dim HourlySalary As Double Dim WeeklySalary As Double

' The following line may produce an error, such as ' if the user types an invalid number HourlySalary = CDbl(InputBox("Enter the employee's hourly salary:"))

' If there was an error, the flow would jump to the label WeeklySalary = HourlySalary * 40

Resume

Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary)) Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary))

Exit Function

ThereWasAProblem: Console.WriteLine("An error occurred when the application executed") Return 0 End Function

End Module

Notice that you can write the Resume operator almost anywhere. In reality, you should identifywhere the program would need to resume. If you want the program to continue with an alternatevalue than the one that caused the problem, in the label section, type Resume Next. Here is anexample:

Module Exercise

Public Function Main() As Integer On Error GoTo ThereWasAProblem

Dim HourlySalary As Double Dim WeeklySalary As Double

' The following line may produce an error, such as ' if the user types an invalid number HourlySalary = CDbl(InputBox("Enter the employee's hourly salary:"))

' If there was an error, the flow would jump to the label WeeklySalary = HourlySalary * 40

Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary)) Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary))

Exit Function

ThereWasAProblem: Console.WriteLine("An error occurred when the application executed")

Resume Next

Return 0 End Function

End Module

We know that in our code, there was probably a problem, which is the reason we presented amessage to the user. Then, when code resumes, where should the compiler go? After all, theproblem was not solved. One way you can deal with the problem is to provide an alternative towhat caused the problem, since you are supposed to know what type of problem occurred. In thecase of an arithmetic calculation, imagine we know that the problem was caused by the usertyping an invalid number (such as typing a name where a number was expected). Instead ofletting the program crash, we can provide an alternate number. The easiest number is 0.

Before asking the compiler to resume, to provide an alternative solution (a number in this case),you can re-initialize the variable that caused the error. Here is an example:

Module Exercise

Public Function Main() As Integer On Error GoTo ThereWasAProblem

Dim HourlySalary As Double Dim WeeklySalary As Double

' The following line may produce an error, such as ' if the user types an invalid number HourlySalary = CDbl(InputBox("Enter the employee's hourly salary:"))

' If there was an error, the flow would jump to the label WeeklySalary = HourlySalary * 40

Page 397: Microsoft Visual Basic 2010 Tutorial

Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary)) Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary))

Exit Function

ThereWasAProblem: Console.WriteLine("An error occurred when the application executed") HourlySalary = 0

Resume Next

Return 0 End Function

End Module

If there are many variables involved, as is the case for us, you can initialize each. Here anexample:

Module Exercise

Public Function Main() As Integer On Error GoTo ThereWasAProblem

Dim HourlySalary As Double, WeeklyTime As Double Dim WeeklySalary As Double

' One of these two lines could produce an error, such as ' if the user types an invalid number HourlySalary = CDbl(InputBox("Enter the employee's hourly salary:")) WeeklyTime = CDbl(InputBox("Enter the time worked for the week:"))

' If there was an error, the flow would jump to the label WeeklySalary = HourlySalary * WeeklyTime

Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary)) Console.WriteLine("Weekly Time: {0}", FormatNumber(WeeklyTime)) Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary))

Exit Function

ThereWasAProblem: Console.WriteLine("An error occurred when the application executed") HourlySalary = 0 WeeklyTime = 0

Resume Next

Return 0 End Function

End Module

Here is an example of running the program:

Hourly Salary: 20.85Weekly Time: 42.50Weekly Salary: 886.13Press any key to continue . . .

Here is another example of running the program:

Page 398: Microsoft Visual Basic 2010 Tutorial

An error occurred when the application executedHourly Salary: 0.00Weekly Time: 38.00Weekly Salary: 0.00Press any key to continue . . .

Here is one more example of running the program:

An error occurred when the application executedAn error occurred when the application executedHourly Salary: 0.00Weekly Time: 0.00Weekly Salary: 0.00Press any key to continue . . .

Types of Error

Introduction

In our introductions to errors, we mostly anticipated only problems related to arithmeticcalculations. In reality, a program can face various categories of bad occurrences. The moreproblems you prepare for, the least headaches you will have. Problems are divided in two broadcategories.

Syntax Errors

A syntax error occurs if your code tries to perform an operation that the Visual Basic languagedoes not allow. These errors are probably the easiest to locate because the Code Editor isconfigured to point them out at the time you are writing your code.

If you try typing or try inserting an operator or keyword in the wrong place on your code, theCode Editor would point it out by underlining it. Here is an example:

In this case, if you were trying to use the Do keyword instead of a data type (probably Double in

Page 399: Microsoft Visual Basic 2010 Tutorial

this case), the Code Editor would show it right away. This type of error is pointed out for everykeyword and operator you try to use.

Notice that, in the above example, we used a valid keyword but at the wrong time. If you mistypea keyword or an operator, you would receive an error. Fortunately, the Code Editor is equipped toknow all keywords of the Visual Basic language. Consider the following example:

The programmer mistyped the Mod operator and wrote MAD instead.

If you forget to include a necessary factor in your code, you would get a syntax error. Forexample, if you are creating a binary arithmetic expression that expects a second operand afterthe operator, you would receive an error. Here is an example:

In this case, the programmer pressed Enter after the Mod operator, as if the expression wascomplete. This resulted in an error.

These are just a few types of syntax errors you may encounter. As mentioned already, if you usethe Code Editor to write your code, most of these errors are easy to detect and fix.

Run-Time Errors

A run-time error occurs when an application tries to do something that the operating system doesnot allow. In some cases, only your application would crash. In some other cases, the user mayreceive a more serious error. As its name indicates, a run-time error occurs when the programruns; that is, after you have created your application.

Fortunately, during the testing phase, you may encounter some of the errors so you can fix thembefore distributing your application. Some other errors may not occur even if you test yourapplication. They may occur to the users after you have distributed your application. For example,you can create a car rental application that is able to display pictures 100% of the time on yourcomputer while locating them from the E: drive. Without paying attention, after distributing yourapplication, the user's computer may not have an E: drive and, when trying to display thepictures, the application may crash.

Examples of run-time errors are:

a. Trying to use computer memory that is not available

b. Performing a calculation that the computer hardware (for example the processor) does notallow. An example is division by 0 (the Intel and AMD processors are equipped not to allow

Page 400: Microsoft Visual Basic 2010 Tutorial

division by 0)

c. Trying to use or load a library that is not available or is not accessible, for any reason

d. Performing an arithmetic operation on two incompatible types (such as trying to assign to anInteger variable the result of adding a string to a Double value)

e. Using a loop that was not properly initialized

f. Trying to access a picture not accessible. Maybe the path specified for the picture is wrong.Maybe your code gives the wrong extension to the file, even though the file exists

g. Accessing a value beyond the allowable range. For example, using a Byte variable to assign aperformed operation that produces a value the variable cannot hold

As you may imagine, because run-time errors occur after the application has been described asready, some of these errors can be difficult to identify. Some other errors depend on the platformthat is running the application (the operating system, the processor, the version of the application,the (available) memory, etc).

The Err Object

Introduction

To assist you with handling errors, the Visual Basic language provides a class named Err. Younever have to declare a variable for this class. An Err object is available whenever you startcreating a Visual Basic project, and you can directly access its properties.

The Error Number

As mentioned already, there are various types of errors that can occur to a program. To assist youwith identifying a problem, the Err class is equipped with a property named Number. Thisproperty is presented as follows:

Public Property Number() As Integer

This property holds a specific number to each sample error that can occur to a program. Becausethere are many types of errors, there are also many numbers, so much that we cannot review allof them. We can only mention some of them when we encounter them.

When a program runs, to find out what type of error occurred, you can question the Numberproperty of the Err object to find out whether the error that has just occurred holds this or thatnumber. To do this, you can use an If...Then conditional statement to check the number. You canthen ask the compiler to display the necessary message to the user. Here is an example:

Module Exercise

Public Function Main() As Integer On Error GoTo ThereWasAProblem

Dim HourlySalary As Double, WeeklyTime As Double Dim WeeklySalary As Double

' One of these two lines could produce an error, such as ' if the user types an invalid number HourlySalary = CDbl(InputBox("Enter the employee's hourly salary:")) WeeklyTime = CDbl(InputBox("Enter the time worked for the week:"))

' If there was an error, the flow would jump to the label WeeklySalary = HourlySalary * WeeklyTime

Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary)) Console.WriteLine("Weekly Time: {0}", FormatNumber(WeeklyTime)) Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary))

Exit Function

ThereWasAProblem: If Err.Number = 13 Then MsgBox("You typed an invalid value") HourlySalary = 0 WeeklyTime = 0

Resume Next End If

Return 0 End Function

End Module

Here is an example of running the program:

Page 401: Microsoft Visual Basic 2010 Tutorial

Hourly Salary: 0.00Weekly Time: 38.50Weekly Salary: 0.00Press any key to continue . . .

The Error Message

As mentioned already, there are many errors and therefore many numbers held by the Numberproperty of the Err object. As a result, just knowing an error number can be vague. To furtherassist you with decrypting an error, the Err object provides a property named Description. Thisproperty holds a short message about the error number. This property works along with theNumber property. It holds the message corresponding to each Number property.

To get the error description, after inquiring about the error number, you can get the equivalentDescription value. Here is an example:

Module Exercise

Public Function Main() As Integer On Error GoTo ThereWasAProblem

Dim HourlySalary As Double, WeeklyTime As Double Dim WeeklySalary As Double

' One of these two lines could produce an error, such as ' if the user types an invalid number HourlySalary = CDbl(InputBox("Enter the employee's hourly salary:")) WeeklyTime = CDbl(InputBox("Enter the time worked for the week:"))

' If there was an error, the flow would jump to the label WeeklySalary = HourlySalary * WeeklyTime

Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary)) Console.WriteLine("Weekly Time: {0}", FormatNumber(WeeklyTime)) Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary))

Exit Function

ThereWasAProblem: If Err.Number = 13 Then MsgBox(Err.Description) HourlySalary = 0 WeeklyTime = 0

Resume Next End If

Return 0 End Function

End Module

Here is an example of running the program:

Page 402: Microsoft Visual Basic 2010 Tutorial

Hourly Salary: 0.00Weekly Time: 40.00Weekly Salary: 0.00Press any key to continue . . .

In some cases, the error message will not be explicit enough, especially if a user simply reads it toyou over the phone. The alternative is to create your own message in the language you easilyunderstand, as we did earlier. If you want, you can also display a message that combines theErr.Description message and your own message. Here is an example:

Module Exercise

Public Function Main() As Integer On Error GoTo ThereWasAProblem

Dim HourlySalary As Double, WeeklyTime As Double Dim WeeklySalary As Double

' One of these two lines could produce an error, such as ' if the user types an invalid number HourlySalary = CDbl(InputBox("Enter the employee's hourly salary:")) WeeklyTime = CDbl(InputBox("Enter the time worked for the week:"))

' If there was an error, the flow would jump to the label WeeklySalary = HourlySalary * WeeklyTime

Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary)) Console.WriteLine("Weekly Time: {0}", FormatNumber(WeeklyTime)) Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary))

Exit Function

ThereWasAProblem: If Err.Number = 13 Then MsgBox(Err.Description & ": The value you typed cannot be accepted.") HourlySalary = 0 WeeklyTime = 0

Resume Next End If

Return 0 End Function

End Module

The Source of the Error

Most of the time, you will know what caused an error, since you will have created the application.The project that causes an error is known as the source of error. In some cases, you may not beable to easily identify the source of error. To assist you with this, the Err object is equipped with aproperty named Source.

To identify the application that caused an error, you can inquire about the value of this property.

Page 403: Microsoft Visual Basic 2010 Tutorial

Previous Copyright © 2009-2010 FunctionX, Inc. Home

Page 404: Microsoft Visual Basic 2010 Tutorial

Events

Introduction

In a typical application, every class is mostly meant to interact with others, either to requestvalues and methods of the other classes or to provide other classes with some values or abehavior they need. When a class A requests a value or service from another class B, class A isreferred to as a client of class B.

This relationship is important not simply because it establishes a relationship between both classesbut also because class B should be ready to provide the value or behavior that a client needs at acertain time.

While a class B is asked to provide some values to, or perform some assignment(s) for, anotherclass A, many things would happen. In fact, there is an order that the actions should follow. Forexample, during the lifetime of a program, that is, while a program is running, a class may beholding a value it can provide to its client but at another time, that value may not be availableanymore, for any reason; nothing strange, this is just the ways it happens. Because differentthings can happen to a class B while a program is running, and because only class B would beaware of these, it must be able to signal to the other classes when there is a change. This is thebasis of events: An event is an action that occurs on an object and affects it in a way that itsclients must be made aware of.

Event Creation

An event is declared like a pseudo-procedure. To actually declare an event, you use the Eventkeyword with the following formula:

[modifier] Event Name(Argument)

The modifier can be Public, Private, Protected, or Friend. The Event keyword is required. It isfollowed by a name for the event. If the event has arguments, enter them in its parentheses.

Here is an example that declares an event:

Module Exercise

Private Event Evidence()

End Module

Raising an Event

To use an event, the object that causes it must initiate it. When this happens, the object is said toraise the event. To assist you with this, the Visual Basic language provides the RaiseEventoperator. To use it, the formula to follow is:

RaiseEvent EventName(Argument(s))

You start with the RaiseEvent keyword followed by the name of the event you would havedeclared previously. The name of the event is followed by parentheses. Here is an example:

Module Exercise Private Event Evidence()

Public Function Main() As Integer RaiseEvent Evidence()

Return 0 End Function

End Module

Events and Delegates

In reality, an event is something that happens to an object in response to a change in behavior.To possible, an event uses a behavior implemented by a delegate. This means that you must firstcreate the delegate. Once the delegate and the event have been declared, you can hook up thedelegate to the event. Then when the appropriate action occurs, the event fires. At that time, theprocedure that implements the delegate runs.

Before using an event, you must specify the procedure that will carry the event. This procedure isreferred to as a handler. To implement this behavior, the event must return a value, and thatvalue must be the delegate that implements the desired behavior. Obviously you must first havecreated a procedure. Here is an example:

Page 405: Microsoft Visual Basic 2010 Tutorial

Module Exercise

Private Sub ShowMessage() MsgBox("Get the necessary message") End Sub

End Module

To add a handler to the program, you use the AddHandler operator with the following formula:

AddHandler EventName, AddressOf Procedure

The AddHandler and the AddressOf operators are required. The EventName placeholder is usedto specify the name of the event that is being dealt with. The Procedure factor is the name of theprocedure that will implement the event. Here is an example:

Module Exercise Delegate Sub Messenger() Private Event Evidence As Messenger

Private Sub ShowMessage() MsgBox("Get the necessary message") End Sub

Public Function Main() As Integer AddHandler Evidence, AddressOf ShowMessage

Return 0 End Function

End Module

Raising an Event

After adding a handler to the event, it is ready but you must launch its action. To do this, you canuse the RaiseEvent operator with the following formula:

RaiseEvent EventName()

The RaiseEvent operator is required. The EventName placeholder is used to specify the name ofthe event, and it must be followed by parentheses. Here is an example:

Module Exercise Delegate Sub Messenger() Private Event Evidence As Messenger

Private Sub ShowMessage() MsgBox("Get the necessary message") End Sub

Public Function Main() As Integer AddHandler Evidence, AddressOf ShowMessage

RaiseEvent Evidence() Return 0 End Function

End Module

A Parameterized Event

The event we used in the previous sections did not take any argument. Just like a delegate, anevent can take an argument. The primary rule to follow is that both its delegate and the procedureassociated with it must take the same type of event. The second rule is that, when raising theevent, you must pass an appropriate event to it. Here is an example:

Module Exercise Delegate Sub Messenger(ByVal Msg As String) Private Event Evidence As Messenger

Private Sub ShowMessage(ByVal ToShow As String) MsgBox(ToShow) End Sub

Public Function Main() As Integer AddHandler Evidence, AddressOf ShowMessage

RaiseEvent Evidence("Is this the last thing to do?") Return 0 End Function

End Module

Just like an event can take an argument, it can also take more than one argument. The primaryrules are the same as those for a single parameter. You just have to remember that you aredealing with more than one argument. Here is an example:

Module Exercise Delegate Sub Messenger(ByVal Originator As String, ByVal Msg As String) Private Event Evidence As Messenger

Private Sub ShowMessage(ByVal Sender As String, ByVal ToShow As String)

Page 406: Microsoft Visual Basic 2010 Tutorial

MsgBox(Sender & ": " & ToShow) End Sub

Public Function Main() As Integer AddHandler Evidence, AddressOf ShowMessage

RaiseEvent Evidence("Message form the Accounting Department", _ "Remember to do your time sheet") Return 0 End Function

End Module

Instead of a parameter of a primitive type, you can create an event that takes a class asargument.

Home Copyright © 2009-2010 FunctionX, Inc.

Page 407: Microsoft Visual Basic 2010 Tutorial

Errors and Exceptions: Introduction toErrors and Debugging

Errors in a Program

Introduction

Problems happen in a program. Some of them manifest themselves while you are developingyour project. Some others would show up during the lifetime of your application. This seams tobe an avoidable fact of life. The errors your program will encounter can be classified in threecategories: runtime, syntax, and logic errors.

Application: Introducing Errors

1. Start Microsoft Visual Studio

2. To create a new application, on the main menu, click File -> New Project...

3. In the middle list, click Console Application

4. Change the Name to WattsALoan1

5. Click OK

6. On the main menu, click Project -> WattsALoan1 Properties

7. Click the arrow of the Application Type box and select Windows Forms Application

8. In the Solution Explorer, right-click Module1.vb and click Rename

9. Type LoanEvaluation.vb and press Enter twice

10. Change the document as follows:

Module LoanEvaluation

Public Function Main() As Integer Return 0 End Function

End Module

Syntax Errors

A syntax error is due to a misuse of the Visual Basic language in your code. For example, theVisual Basic language has a set of keywords that you should (must) not use to name your variable.This rule is usually easy to respect if you are using a professional text editor such as the CodeEditor of Microsoft Visual Basic.

The Code Editor of Microsoft Visual Basic makes it easy to be aware of syntax errors as soon asthey occur:

When you start typing code, the IntelliSense starts building a list of words that match the firstcharacters and those that include the characters already typed:

Page 408: Microsoft Visual Basic 2010 Tutorial

If you see a word you need and it is highlighted, you can press Enter to select it. You can alsodouble-click the word from the list. If the list is long and the word does not appear yet, youcan keep typing (adding characters) until the word you want comes up

If you mistype a word or a keyword, the Code Editor would indicate the error by underliningthe word. If you place the mouse on it, a message would display the reason for the error:

If you declare a variable, or once you have declared a variable, whenever you want to use it,as soon as you start typing its name, the IntelliSense would display a list that includes thatvariable

The Visual Basic language is equipped with many operators and each operator has rules. If youmisuse an operator, the section of your code would be underlined. You can position the mouseon it to see the resulting error message:

As you can see, if you create your application in Microsoft Visual Studio, the Code Editor is fullyequipped with tools to assist you to detect and correct syntax errors. If you still violate a syntaxrule, when you build your project, the compiler would detect the error and point out the line, thesection, and the file name where the error occurred (we will come back to this in the next lesson).

Application: Introducing Syntax Errors

Change the document as follows:

Module LoanEvaluation

Public Function Main() As Integer Dim Summary As String Dim Principal As Double = 0.0

Summary = "Watts A Loan?" & vbCrLf

Summary += "============================" & vbCrLf Summary += "Loan Summary" & vbCrLf Summary += "=------------------------------------------=" & vbCrLf Summary += String.Format("Principal: {0:F}" & vbCrLf, Principal) Summary += "============================"

MsgBox(Summary) Return 0

Page 409: Microsoft Visual Basic 2010 Tutorial

End Function

End Module

Logic Errors

A logic error occurs when the program (the code) is written fine but the result it produces is notreliable. With a logic error, the Code Editor does not see anything wrong in the document andtherefore cannot point out a problem. One of the worse types of logic errors is one that makes acomputer crash sometimes, regularly, or unpredictably, while there is nothing obviously wrong inthe code.

Logic errors are, or can be, difficult to spot because you will have to know for sure that the resultis wrong and why (and sometimes worse, you will have to agree or accept that it is your programthat is causing a problem in the computer; imagine a user reports that her computer crashes everytime she starts the application you created). Because you or the user of your program would knowwith certainty that the result is questionable, you would have to use some means of correcting it.One of the techniques you can use is referred to as debugging.

Debugging Fundamentals

Introduction

A logic error is called a bug. Debugging is the process of examining code to look for bugs or toidentify problems. Debugging is the ability to monitor the behavior of a variable, a function, oranother item throughout a program. Microsoft Visual Basic provides many features to performdebugging operations.

The debugger is the program you use to debug your code. The code or application that you aredebugging is called the debuggee.

Probably the most fundamental way of examining code is to read every word and every line, withyour eyes, using your experience as a programmer. This can work for short code written in one fileand in one class. If the code to examine covers many pages or many files, it could be aweful andtiresome to examine code with your eyes line by line. Fortunately, to assist you with thisoperation, Microsoft Visual Studio provides various tools and windows that you use, one window ora combination of objects. One of the tools you can use is the Standard toolbar that is equippedwith various debugging buttons:

Starting and Continuing With Debugging

There are different ways you can launch the debugging process:

On the main menu, you can click Debug -> Start Debugging

On the Standard toolbar, you can click the Start Debugging button

In the Solution Explorer, you can right-click the name of the project, position the mouse onDebug, and click Step Into New Instance

You can press F5

In later sections, we will see other ways of starting or proceeding with debugging. In some cases,we will see how you can suspend debugging. When this has happened, to resume debugging:

On the main menu, you can click Debug -> Continue

On the Standard toolbar, you can click the Continue button

You can press F5

We will see other ways of continuing with debugging.

Stopping the Debugging

As we will see in later sections, there are various debugging approaches available in MicrosoftVisual Studio. Sometimes you will want to suspend or stop debugging.

To end debugging at any time:

On the main menu, click Debug -> Stop Debugging

On the Standard toolbar, click the Stop Debugging button

The Locals Window

Page 410: Microsoft Visual Basic 2010 Tutorial

One of the primary pieces of information you want to get is the value that a variable is holding. Awindow named Locals can be used to show that value. Normally, when you start debugging, theLocals window shows automatically. During debugging, if the Locals window is hidden, to displayit:

On the main menu, click Debug -> Windows -> Locals

Press Ctrl + Alt + V, release, then press L

As its name indicates, the Locals window shows the values of local variables as they are changed.If there is more than one variable, the Locals window displays their names and gives a row toeach variable. The Locals window organizes its information in a table or grid:

The Name column shows the name of each variable declared in the method or the section that isbeing debugged. If the variable is a class, a + button appears to its left, indicating that it hasfields (member variables):

In this case, to show the variables, that is, to expand the node, click the + button. This wouldshow the fields under the variable name and the name of the class between curly brackets underthe Value column:

The Value columns shows the value of each variable. When debugging starts, each variable showsits default value. As debugging progresses, when a variable acquires a new value, the Localswindow updates it in the Value column. In some cases, instead of the debugger changing thevalue, you can manually select and change it in the Locals window and press Enter.

The Type column shows the data type of the variable. If the variable is a class, the name of theclass shows in the Type column.

Debugging Statements

Executing One Statement at a Time

Just as done when reading code with your eyes, the most basic way to monitor code is to executeone line at a time and see the results. To support this operation, the debugger provides what isreferred to as stepping into.

To execute code one line at a time, while the file that contains it is displaying:

On the main menu, click Debug -> Step Into

On the Standard toolbar, click the Step Into button

In you are using Microsoft Visual Studio, press F8.If you are using Microsoft Visual Basic 2010 Express, press F11

Page 411: Microsoft Visual Basic 2010 Tutorial

When code is being stepped into, the margin corresponding to the line that is being examineddisplay a right-pointing yellow arrow:

This lets you know what line is currently considered.

Application: Examining Local Variables

1. While the Code Editor is displaying the code you typed, on the main menu, click Debug ->Step Into

2. To display the Locals window, on the main menu, click Debug -> Window -> Locals

3. Notice the yellow arrow button in the margin.Notice that the Locals window displays the name of the Main function and the variables in the

Page 412: Microsoft Visual Basic 2010 Tutorial

function.To end debugging, on the main menu, click Debug -> Stop Debugging

4. Change the code as follows:

Module LoanEvaluation

Public Function Main() As Integer Dim Summary As String Dim Principal As Double Dim InterestRate As Double Dim Period As Double Dim InterestAmount As Double Dim FutureValue As Double

Summary = "This application allows you to evaluate a loan." & vbCrLf Summary += "To proceed, enter the following values" & vbCrLf MsgBox(Summary, MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, "Watts A Loan?")

Principal = CDbl(InputBox("Enter the principal: ", "Watts A Loan?", "0.00")) InterestRate = CDbl(InputBox("Enter the interest rate: ", "Watts A Loan?", "0.00")) / 100 Period = CDbl(InputBox("Enter the number of months: ", "Watts A Loan?", "0.00")) / 12

InterestAmount = Principal * InterestRate * Period FutureValue = Principal + InterestAmount

Summary = "Watts A Loan?" & vbCrLf Summary += "========================" & vbCrLf Summary += "Loan Summary" & vbCrLf Summary += "-------------------------------------" & vbCrLf Summary += "Principal:" & vbTab & vbTab & Principal.ToString("F") & vbCrLf Summary += "Interest Rate:" & vbTab & InterestRate.ToString("P") & vbCrLf Summary += "Period:" & vbTab & vbTab & CStr(Period * 12) & " months" & vbCrLf Summary += "Interest Amount:" & vbTab & InterestAmount.ToString("F") & vbCrLf Summary += "Future Value:" & vbTab & FutureValue.ToString("F") & vbCrLf Summary += "========================"

MsgBox(Summary, MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, "Watts A Loan?") Return 0 End Function

End Module

5. To restart debugging, on the main menu, click Debug -> Step Into.Notice that the Locals window displays a list of the local variables and their starting values:

6. To continue debugging, on the Standard toolbar, click the Step Into button

7. To continue debugging, press F8 twice

8. Keep pressing F8 until a message box displays

Page 413: Microsoft Visual Basic 2010 Tutorial

9. Click OK

10. Keep pressing F8 until an input box displays

11. When asked to enter a value for the principal, type 6500 and press Enter

12. When you are asked to provide the interest rate, type 12.65 and press Enter

13. Press F8

14. Press F8 again

15. When the number of months is requested, type 36 and press Enter.Notice that the value of the period variable in the Locals window has been changed

16. Press F8

17. Press F8

Page 414: Microsoft Visual Basic 2010 Tutorial

18. Press F8

19. Continue pressing F8 until the Summary message box displays

20. Click OK to close the message box

Running to a Point

When executing a program, you can specify a section or line where you want the execution topause, for any reason you judge necessary. This approach is useful if you have checked code up toa certain point and it looked alright. If you are not sure about code starting at a certain point, thiscan be your starting point.

To execute code up to a certain point

Right-click the line and click Run to Cursor

Press Ctrl + F8

Application: Running to a Point

1. In the code, right-click the Summary = "Watts A Loan?" & vbCrLf line and click Run ToCursor

2. When requested, enter the following values. Press Enter after entering each value. While youare entering them, check the moving button in the Code Editor and observe the values in theLocals window: Principal 2450.00

Interest Rate 10.15

Period 28

Page 415: Microsoft Visual Basic 2010 Tutorial

3. Press F5 to continue

Breakpoints

A breakpoint on a line is the code where you want the exection to suspend. You must explicitlyspecify that line by creating a breakpoint. You can aslo create as many breakpoints as you want.You can also remove a breakpoint you don't need anymore.

To create a breakpoint, first identify the line of code where you want to add it. Then:

In the left margin corresponding to the line, click

On the main menu, click Debug -> Toggle Breakpoint

Right-click the line, position the mouse on Breakpoint, and click Insert Breakpoint

Click anything on the line and press F9

A breakpoint is represented by a red circular button . After creating a breakpoint, when codeexecutes and reaches that line, it would pause and let you know by drawing a right-pointing yellowbutton .

After using a breakpoint, you can remove it. To delete a breakpoint:

Click the breakpoint in the margin

Right-click the line that has the breakpoint, position the mouse on Breakpoint, and click DeleteBreakpoint

Click anything on the line that has the breakpoint:

On the main menu, click Debug -> Toggle Breakpoint

Press F9

Remember that you can create more than one breakpoint. If you have more than one breakpoint inyour code, execution would pause at each one of them. At any time, you can remove one or allbreakpoints. To delete all breakpoints, on the main menu, click Debug -> Delete all Breakpoints.

Application: Using Breakpoints

1. In the Code Editor, click the margin on the left side of FutureValue = Principal +InterestAmount

Page 416: Microsoft Visual Basic 2010 Tutorial

2. On the main menu, click Debug -> Start Debugging

3. Click OK on the message box

4. When asked, enter the values as follows and press Enter after each Principal 1500

Interest Rate 15.55

Period 24

5. Press F5 to continue

Page 417: Microsoft Visual Basic 2010 Tutorial

6. In the Code Editor, click the FutureValue = Principal + InterestAmount line

7. On the main menu, click Debug -> Toggle Breakpoint

8. In the Code Editor, click the Principal = CDbl(InputBox("Enter the principal: ", line

9. On the main menu, click Debug -> Toggle Breakpoint

10. In the Code Editor, right-click the Summary = "Watts A Loan?" & vbCrLf line, position themouse on Breakpoints, and click Insert Breakpoint

11. To execute, press F5

12. Click OK on the message box.Notice the first breakpoint has changed

Page 418: Microsoft Visual Basic 2010 Tutorial

13. To continue, press F5

14. When asked, enter the values as follows and press Enter after each Principal 17500

Interest Rate 9.75

Period 48

15. Press F5 to continue

16. Click OK to close the message box

Page 419: Microsoft Visual Basic 2010 Tutorial

Stepping to Breakpoints

You can combine the Step Into feature with breakpoints. That is, you can examine each code lineafter line until you get to a specific line. This allows you to monitor the values of variables and seetheir respective values up to a critical section. To do this, first create one or more breakpoints,then proceed with Step Intos of your choice.

Application: Stepping to Breakpoints

1. Make sure the previous two breakpoints are still selected.To start debugging, on the main menu, click Debug -> Step Into.Make sure you can see the Code Editor and the Locals window

2. Press F8 continually until the message box displays

3. Click OK on the message box

4. To continue, press F8 to step into

5. Enter the principal as 3525.75 and click OK

6. Press F8 to continue

7. Enter the interest rate as 13.75 and click OK

8. Press F8 to continue

9. Enter the period as 32 and click OK

10. Press F5 twice to continue

11. Click OK on the message box

Executing One Method at a Time

The Step Into feature is a good tool to monitor the behavior of variables inside a procedure. Thisalso allows you to know if a procedure is behaving as expected. Once you have established that aprocedure is alright, you may want to skip it. Instead of executing one line at a time, thedebugger allows you to execute a whole procedure at a time or to execute the lines in someprocedures while skipping the others. To support this, you use a feature named Step Over.

To step over a method, while debugging:

On the main menu, click Debug -> Step Over

On the Standard toolbar, click the Step Over button

Press Shift + F8

As its name suggests, the Step Over feature allows you to skip a procedure if you know it doesn'thave any problem. When debugging, you choose what procedures to step into and which ones tostep over.

Application: Stepping Over

1. Change the document as follows:

Module LoanEvaluation Private Sub Announce() MsgBox("This application allows you to evaluate a loan." & vbCrLf & "To proceed, enter the following values" & vbCrLf, MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, "Watts A Loan?") End Sub

Private Function GetPrincipal() As Double Dim PresentValue As Double

REM Price of a car PresentValue = 22755.85

Return PresentValue End Function

Private Function GetInterestRate() As Double Dim Rate As Double

Rate = 14.55

Return Rate End Function

Private Function GetPeriod() As Integer Dim Months As Integer

Months = 60

Return Months

Page 420: Microsoft Visual Basic 2010 Tutorial

End Function

Public Function Main() As Integer Dim Principal As Double Dim InterestRate As Double Dim Period As Double Dim InterestAmount As Double Dim FutureValue As Double

Announce() Principal = GetPrincipal() InterestRate = GetInterestRate() Period = GetPeriod() Return 0 End Function

End Module

2. To debug, on the main menu, click Debug -> Step Into.Notice that the yellow button is positioned in the margin on the left of the Main() function

3. To continue debugging, on the Standard toolbar, click the Step Into button four times

4. Click OK on the message box

5. Click the Step Into button again two times.Notice the yellow margin button is positioned on Principal = GetPrincipal()

6. Click the Step Into button and notice that the yellow-point button is positioned on thestarting point of the GetPrincipal() function

7. Click the Step Into button again.Notice that the debugging is continuing in the body of the GetPrincipal() function and visitseach line

8. Click the Step Into button again three times to complete debugging the GetPrincipal()function

9. To stop the debugging, on the Standard toolbar, click the Stop Debugging button

10. To debug, on the main menu, click Debug -> Step Into.Notice that the yellow button is positioned in the margin

11. To continue, on the Standard toolbar, click the Step Into button four times

12. Click OK on the message box

13. Click the Step Into button twice until the yellow margin button is positioned on thePrincipal = GetPrincipal() line

14. To skip the GetPrincipal() function, on the main menu, click Debug -> Step Over.Notice that, this time, the body of the GetPrincipal() function is skipped

15. Click the Step Into button

16. To stop the debugging, on the main menu, click Debug -> Stop Debugging

17. Change the document as follows:

Module LoanEvaluation Private Sub Announce() MsgBox("This application allows you to evaluate a loan." & vbCrLf & "To proceed, enter the following values" & vbCrLf, MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, "Watts A Loan?") End Sub

Private Function GetPrincipal() As Double Dim PresentValue As Double

PresentValue = CDbl(InputBox("Enter the principal: ", "Watts A Loan?", "0.00")) Return PresentValue End Function

Private Function GetInterestRate() As Double Dim Rate As Double

Rate = CDbl(InputBox("Enter the interest rate: ", "Watts A Loan?", "0.00")) Return Rate End Function

Private Function GetPeriod() As Integer Dim Months As Integer

Months = CDbl(InputBox("Enter the number of months: ", "Watts A Loan?", "0.00")) Return Months

Page 421: Microsoft Visual Basic 2010 Tutorial

End Function

Private Sub ShowSummary(ByVal Principal As Double, ByVal AnnualRate As Double, ByVal Periods As Integer, ByVal InterestCollected As Double, ByVal TotalCollected As Double) MsgBox("Watts A Loan?" & vbCrLf & "========================" & vbCrLf & "Loan Summary" & vbCrLf & "-------------------------------------" & vbCrLf & "Principal:" & vbTab & vbTab & Principal.ToString("F") & vbCrLf & "Interest Rate:" & vbTab & AnnualRate.ToString("P") & vbCrLf & "Period:" & vbTab & vbTab & CStr(Periods * 12) & " months" & vbCrLf & "Interest Amount:" & vbTab & InterestCollected.ToString("F") & vbCrLf & "Future Value:" & vbTab & TotalCollected.ToString("F") & vbCrLf & "========================", MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, "Watts A Loan?") End Sub

Public Function Main() As Integer Dim Principal As Double Dim InterestRate As Double Dim Period As Double Dim InterestAmount As Double Dim FutureValue As Double

Announce() Principal = GetPrincipal() InterestRate = GetInterestRate() / 100 Period = GetPeriod() / 12

InterestAmount = Principal * InterestRate * Period FutureValue = Principal + InterestAmount

ShowSummary(Principal, InterestRate, Period, InterestAmount, FutureValue) Return 0 End Function

End Module

18. To debug, on the Standard toolbar, click the Step Into button

19. To continue, press F8 four times

20. Click OK on the message box

21. Press F8 two times and notice the yellow margin button is positioned on Principal =GetPrincipal()

22. Press F8 to start debugging the GetPrincipal() function

23. Press F8 and notice that the debugging is continuing in the body of the GetPrincipal() functionline by line

24. When asked for the principal, type 21650 and press Enter

25. Press F8 twice

26. To stop the debugging, on the Standard toolbar, click the Stop Debugging button

27. To debug again, press F8 five times

28. Click OK on the message box

29. Click the Step Into button twice until the yellow margin button is positioned on thePrincipal = GetPrincipal() line

30. To avoid debugging line after line in the GetPrincipal() function, on the main menu, clickDebug -> Step Over

31. When asked to give the principal, type 3600 and press Enter

32. Click the Step Into button

33. Keep pressing the Step Over button

34. When asked to provide the interest rate, type 14.05 and press Enter

35. Continue stepping over

36. When asked to provide the number of months, type 48 and press Enter

37. Continue stepping over to the end

38. On the main menu, click Debug -> Delete All Breakpoints

39. On the main menu, click File -> Close Project or File -> Close Solution

40. When asked whether you want to save, click Discard

Page 422: Microsoft Visual Basic 2010 Tutorial

Home Copyright © 2010 FunctionX, Inc.

Page 423: Microsoft Visual Basic 2010 Tutorial

Errors and Exceptions: Options onDebugging

Debugging and Separate Files

Introduction

In the previous sections, we dealt with one or a few procedure in only one file. As you knowalready, a program can use many files, some files come from the .NET Framework you create theothers as you judge them necessary for your project. As a result, when debugging, you canconsider files that are linked at one time or another. The process of debugging is primarily thesame. You just have to keep in mind that you are dealing with different files. This has someconsequences on the results you see.

Application: Debugging With a Class

1. Start Microsoft Visual Basic

2. To start a new project, on the main menu, click File -> New Project...

3. In the middle list, click Console Application

4. Change the Name to WattsALoan2

5. Click OK

6. On the main menu, click Project -> WattsALoan2 Properties

7. Click the arrow of the Application Type box and select Windows Forms Application

8. To create a new class, in the Solution Explorer, right-click WattsALoan2 -> Add -> Class...

9. In the middle list, make sure Class is selected.Change the Name to Customer and click Add

10. Change document as follows:

Public Class Customer Public FullName As String Public PhoneNumber As String

Public Sub New(Optional ByVal Name As String = "John Doe", Optional ByVal Phone As String = "000-000-0000") FullName = Name PhoneNumber = Phone End SubEnd Class

11. To create a new class, in the Class View, right-click WattsALoan2 -> Add -> Class...

12. Change the Name to Employee and press Enter

13. In the empty document, type the following:

Public Class Employee Public EmployeeNumber As Long Public FirstName As String Public LastName As String Public Title As String

Public Sub New(Optional ByVal EmplNbr As Long = 0, Optional ByVal FName As String = "Unknown", Optional ByVal LName As String = " Not Specified", Optional ByVal Position As String = "Loan Specialist") EmployeeNumber = EmplNbr FirstName = FName LastName = LName Title = position End Sub

Public Function GetEmployeeName() As String Return LastName + ", " + FirstName End FunctionEnd Class

14. To add a new class to the project, on the main menu, click Project -> Add Class...

15. Change the Name to LoanInformation

16. Click Add

17. In the empty document, type the following:

Page 424: Microsoft Visual Basic 2010 Tutorial

Public Class LoanInformation Public Principal As Double Public InterestRate As Double Public Period As Double Public InterestAmount As Double Public FutureValue As DoubleEnd Class

18. In the Solution Explorer, right-click Module1.vb and click Rename

19. Type LoanEvaluation.vb and press Enter twice

20. In the empty document, type the following:

Using Separate Files

Instead of just one class or one file, we have learned that, to organize your project, you cancreate classes in different files. When you debug a project that uses different files that containprocedures and classes, the debugger is aware of the objects and where they are located. As wewill learn later, there are various windows that assist you with identifying the objects of yourproject. As a result, the tools such as the Locals window display their contents accordingly.

Module LoanEvaluation Private Clerk As Employee Private Client As Customer Private Loan As LoanInformation

Private Sub IdentifyEmployee() MsgBox("Enter the following pieces of information " + "about the employee who prepared this loan.") Clerk.EmployeeNumber = CLng(InputBox("Employee #: ", "Watts A Loan?", "000000")) Clerk.FirstName = InputBox("First Name:") Clerk.LastName = InputBox("Last Name:") Clerk.Title = InputBox("Title:") End Sub

Private Sub IdentifyCustomer() MsgBox("Enter the following pieces of information " + "about the customer for whom this loan was prepared.") Client.FullName = InputBox("Customer Name:") Client.PhoneNumber = InputBox("Phone Number:") End Sub

Private Sub GetLoanValues() MsgBox("Enter the following pieces of information " + "about the values used for the loan.") Loan.Principal = CDbl(InputBox("Enter the principal:")) Loan.InterestRate = CDbl(InputBox("Enter the interest rate:")) / 100 Loan.Period = CDbl(InputBox("Enter the number of months:")) / 12 End Sub

Public Sub Show() loan.InterestAmount = loan.Principal * loan.InterestRate * loan.Period loan.FutureValue = loan.Principal + loan.InterestAmount

MsgBox("Watts A Loan?" & vbCrLf & "========================" & vbCrLf & "Loan Summary" & vbCrLf & "-------------------------------------" & vbCrLf & "Prepared by:" & vbTab & Clerk.EmployeeNumber & vbCrLf & vbTab & vbTab & Clerk.GetEmployeeName() & vbCrLf & vbTab & vbTab & Clerk.Title & vbCrLf & "Prepared for:" & vbTab & Client.FullName & " - " & Client.PhoneNumber & vbCrLf & "-------------------------------------" & vbCrLf & "Principal:" & vbTab & vbTab & Loan.Principal.ToString("F") & vbCrLf & "Interest Rate:" & vbTab & Loan.InterestRate.ToString("P") & vbCrLf & "Period:" & vbTab & vbTab & CStr(Loan.Period * 12) & " months" & vbCrLf & "Interest Amount:" & vbTab & Loan.InterestAmount.ToString("F") & vbCrLf & "Future Value:" & vbTab & Loan.FutureValue.ToString("F") & vbCrLf & "========================", MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, "Watts A Loan?") End Sub Public Function Main() As Integer Dim Clerk As Employee = New Employee Dim Client As Customer = New Customer Dim Loan As LoanInformation = New LoanInformation

MsgBox("This application allows you to evaluate a loan", MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, "Watts A Loan?") IdentifyEmployee() IdentifyCustomer()

GetLoanValues()

Show() Return 0 End Function

End Module

Page 425: Microsoft Visual Basic 2010 Tutorial

As you know already, the starting point of a Visual Basic application is the Main() procedure. Ifyou start debugging an application that uses many code files, the debugger must first identify thefile that contains the Main() procedure. If you are debugging a normal console application and ifthe debugger cannot find a file that contains the Main() function, you would receive an error,indicating that your project does not contain an entry point.

Application: Debugging Classes

1. To start debugging, on the main menu, click Debug -> Step Into.If you don't see the Locals window, on the main menu, click Debug -> Window -> Locals

2. Notice that the debugging yellow arrow indicator is positioned on the left of the Main()function.To continue debugging, on the main menu, click Debug -> Step Into

3. Again, on the main menu, click Debug -> Step Into

4. Read the message box and click OK

5. Press F8 three times until a message box comes up

6. Click OK on the message box.Notice that the debugging gets in the body of the IdentifyEmployee() function

7. To continue, press F8Notice that the debugger jumps to the Employee.vb file

8. In the Locals window, click the + button of Me to expand it. Notice that it shows the membervariables of the class

9. To continue debugging, on the Standard toolbar, click the Step Into button continually todebug the Employee class and observe the values in the Locals window

10. Continue stepping into until the debugger switches back to the LoanEvaluation.vb file

11. Press F8 and notice that the IdentifyEmployee() function gets focus

12. Press F8 again twice

13. When requested, enter the Employee # as 80226 and click OK

14. Click the Step Into button

15. When asked for the first name, type David and click OK

16. Press F8

17. For the last name, type Boyton and click OK

18. Press F8

19. For the title, type Shift Supervisor and click OK.Observe the values in the Locals window

Page 426: Microsoft Visual Basic 2010 Tutorial

20. Press F8 a few times until the debugger gets to the Client = IdentifyCustomer() line

21. To continue, press F8 and observe the debugging

22. Click OK on the message box

23. Continue pressing F8 until the Customer.vb file gets focus

24. Continue pressing F8 until focus gets back to the LoanEvaluation.vb file

25. In the Locals window, click the + button of Me to expand it

26. Press F8 to continue debugging

27. When asked for the customer name, type Ann Nanze and click OK

28. Press F8

29. When asked for the phone number, type (106) 042-8636 and click OK

30. To continue debugging, press F8 a few times until a message box comes up

31. Read the message box and click OK

32. Press F8 to continue

33. In the Locals window, click the + button

34. Press F8 twice

35. When the principal is requested, type 1000 and click OK

36. Press F8

37. For the interest rate, type 16.05 and click OK

38. Press F8

39. For the period, enter 12 and click OK

40. Press F8

41. In the Locals window, click the second + button

Page 427: Microsoft Visual Basic 2010 Tutorial

42. On the Standard toolbar, click the Step Into button

43. In the Locals window, expand the nodes

44. Press F8

45. In the Locals window, expand the las + node to see the current values of the variables

46. Keep pressing F8 continually. Observe the evolution in the Code Editor and the values in theLocals window

47. When the message box comes up, review it and click OK

Page 428: Microsoft Visual Basic 2010 Tutorial

48. On the main menu, click File -> Close Solution or File -> Close Project

49. When asked whether you want to save, click Discard

The Error List

You are probably familiar with the Error List window because if you have ever made any mistakein your code, it would come up. The Error List is a window that displays the list of the currenterrors in your code. Most of the times, the Error List is present, usually below the Code Editor. Atany time, to display it, on the main menu, you can click View -> Error List or press Ctrl + W.While you are working on your code, the Error List may be minimized. To permanently keep itshowing, you can click its AutoHide button.

The Error List uses two sequences of how it decides to show the errors. While writing your code, ifthe live parser, which continuously runs while you are writing your code, finds a problem, it makesa list of all types of violations, even if there is only one mistake, or there appears to be only onemistake. It shows the list in a table:

Page 429: Microsoft Visual Basic 2010 Tutorial

Another sequence or a different list may gets created if you build your code. This time, it would bethe debugger's list. It is important to know that one mistake could be violating more than one ruleof the Visual Basic language.

As seen in our introduction to syntax errors, if you are using Microsoft Visual Basic (whetherMicrosoft Visual Basic 2010 Express or Microsoft Visual Studio), while you are writing your code, ifthe parser senses a problem, it underlines the section in the Code Editor and the Error List showsits analysis of that problem. The Error list uses a table made of 5 columns that are Description,File, Line, Column, and Project. You don't have to use all those columns. To specify what columnsto show or hide, right-click anywhere in the body of the Error List and position the mouse onShow Columns:

To show a column, put a check mark on its menu item. To hide a column, remove its check mark.The list of errors displays in an incremental order specified by the parser. Otherwise, you canarrange the order based on a column of your choice. To do this, right-click any entry in the ErrorList, position the mouse on Sort By, and click the column of your choice.

As mentioned already, the Error List uses various columns to show its findings:

The Description column shows a string that translates some meaning of the problem. Theparser and the Error List make an effort to point the actual problem. Sometimes, the errorpointed out is not easy to understand. Some other time, the error may not be completely true.Sometimes, if you fix one problem, all the other problems are solved. In our lessons, it isimpossible to list all types of errors or all possible types of errors. With experience, you willknow how to address and correct them

The File column shows the name of the file. This is valuable if your project includes many files

The Line column is probably a junior programmer's best friend. The Error List strives to displaythe line number in code where the problem happened, or probably happened. With experience,you will know that this is not always exact

Like the Line number, the Column attempts to exactly point out the character area where theproblem occurrent. Also with experience, you will find out that the Error List sometimes showswhere it sensed the problem, not necessairy when it happened

The Project column gives the name of the project in which the error occurred. This can bevaluable if you are working on many projects, or rather on a solution that includes manyprojects

Page 430: Microsoft Visual Basic 2010 Tutorial

To jump to an error from the Error List, locate the error and double-click it. The caret would bepositioned to that Line number, that character Column or word, and in that File of that Project. Ifyou correct the problem and if the parser concludes that your correction is fine, the error would beautomatically removed from the Error List. You can continue this to correct all problems and,eventually, the Error List would be emptied.

Objects Assisting With Debugging

The Immediate Window

The Immediate window is a special text editor that can be used to test values, operations(calculations), variables, and (methods of) classes. There are two ways you can get the Immediatewindow:

If you start debugging code from clicking Debug -> Start Debugging (or pressing F5) or Debug-> Step Into (or pressing F8) from the main menu, the Immediate window would come up

If you are not debugging, on the main menu, you can click Debug -> Windows -> Immediate

The Immediate window appears as a blank object:

To use it, you must write something. What you write depends on what you want to test. Anexpression you write should start with a question mark but in some cases you can omit thatsymbol. Because the Immediate window is a text editor, you can copy code from somewhere elseand paste it in it. If the immediate window starts being crowded, to empty it, you can right-clickinside the window and click Clear All.

After typing or pasting the expression, press Enter. The next line would show the result. Forexample, imagine you want to test an arithmetic operation such as the addition of 248.49 and57.26, you would type ?248.49 + 57.26 (the empty spaces are optional and you can include asmany as you want) and press Enter. Here is an example:

If you want to test a variable or a function, you must first write code that has the variable. Thatis, before testing a variable, create a function or use the Main() function and declare the variablein it. If you try testing a variable that is not declared, you would receive an error. One way youcan test a variable consists of assigning a certain value, probably a wrong value (called a testvalue), to it and observe the result. You can start the assignment expression with a question markbut that mark is not necessary. Here is an example:

Page 431: Microsoft Visual Basic 2010 Tutorial

The Immediate window allows you to test the value that a variable is currently holding. To get thisinformation, in the Immediate window, type the name of the variable and press Enter:

If the variable had previously received a value, when you enquire of it in the Immediate window,its current value would show:

Page 432: Microsoft Visual Basic 2010 Tutorial

Another test you can perform on a variable consists of adding a value to it to increase it orsubtracting a value from it.

To test a procedure in the Immediate window, it must be a function. To get the value that afunction is currently returning, type its name preceded by a question mark in the Immediatewindow and press Enter. Here is an example:

In the same way, you can create more elaborate functions and test them in the Immediatewindow.

Page 433: Microsoft Visual Basic 2010 Tutorial

Application: Using the Immediate Window

1. To start a new project, on the main menu, click File -> New Project

2. In the middle list, click Console Application

3. Change the Name to PayrollEvaluation1

4. Click OK

5. On the main menu, click Project -> PayrollEvaluation1 Properties

6. Click the arrow of the Application Type box and select Windows Forms Application

7. In the Solution Explorer, right-click Module1.vb and click Rename

8. Type Evaluation.vb and press Enter twice

9. Change the document as follows:

10. To execute the application, on the main menu, click Debug -> Start Debugging

11. Press Enter to close the message box and return to your programming environment

12. To step into code, on the main menu, click Debug -> Step Into

13. If the Imediate window is not displaying, on the main menu, click Debug -> Windows ->Immediate.Just in case, right-click inside the Immediate window and click Clear All.Click inside the Immediate window

14. Type TimeWorked = 42.50 and press Enter

15. Type HourlySalary = 24.65 and press Enter

16. Type TotalDeductions = 286.50 and press Enter

Module Evaluation

Public Function Main() As Integer Dim GrossPay As Double Dim TimeWorked As Double Dim HourlySalary As Double Dim TotalDeductions As Double Dim NetPay As Double Dim Result As String

Result = "Payroll Evaluation" & vbCrLf GrossPay = HourlySalary * TimeWorked netPay = grossPay - totalDeductions

Result += "===================" & vbCrLf & "Payroll Evaluation" & vbCrLf & "------------------------------" & vbCrLf & "Time Worked:" & vbTab & TimeWorked.ToString("F") & vbCrLf & "Hourly Salary:" & vbTab & HourlySalary.ToString("F") & vbCrLf & "Gross Pay:" & vbTab & vbTab & GrossPay.ToString("F") & vbCrLf & "Deductions:" & vbTab & TotalDeductions.ToString("F") & vbCrLf & "Net Pay:" & vbTab & vbTab & NetPay.ToString("F") & vbCrLf & "==================="

MsgBox(Result, MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, "Payroll Evalueation") Return 0 End Function

End Module

Page 434: Microsoft Visual Basic 2010 Tutorial

17. If you are using Microsoft Visual Basic 2010 Express, press F11 to step into code.If you are using Microsoft Visual Studio, press F8 to step into code

18. Continue stepping into code until the debugger gets to the Result +="===================" & vbCrLf & line

19. Click the next empty line in the Immediate window

20. Type ?GrossPay and press Enter

21. Type ?NetPay and press Enter

Page 435: Microsoft Visual Basic 2010 Tutorial

22. Press the F8 or F11 key to step into code a few times until the message box displays

23. Press Enter to return to Microsoft Visual Basic

The Autos Window

As debugging progresses, sometimes you may want to know the values that the variables areholding on the current and the preceding lines. To give you this information, Microsoft VisualStudio provides (Microsoft Visual Basic 2010 Express doesn't have) the Autos window. Normally,when you start debugging, the Autos window comes up. If it is hidden while you are debugging, onthe main menu, click Debug -> Windows -> Autos.

The Watch Window

Imagine you have a variable that is accessed in various parts of your code. One way you can testthe behavior of that variable is to test its value as it circumstancially changes time after time. TheWatch window is an object that allows you to monitor the values that a variable (or manyvariables) holds (or have) in various parts of a method.

To get the Watch window, start debugging your application (Debug -> Start Debugging or Debug -

Page 436: Microsoft Visual Basic 2010 Tutorial

> Step Into). The Watch window would appear, usually next to the Locals window. The Watchwindow appears as a table with three columns. Their roles will be obvious to you once the windowcontains something.

To actually use the services of a Watch window, you must create one or more entries, which arereferred to as watches. Before creating a watch, you must start stepping into your code, which isdone by clicking Debug -> Step Into or by pressing F8 (Microsoft Visual Studio) or F11 (MicrosoftVisual Basic 2010 Express). If the Watch window doesn't display in Microsoft Visual Basic 2010Express, on the main menu, click Debug -> Window -> Watch.

To create a watch, if you are using Microsoft Visual Studio, on the main menu, click Debug ->QuickWatch... In the Expression combo box, type the name of the variable you want to watch.Here is an example:

You can also type an expression such as a value added to a variable. Here is an example:

If you want to submit the entry, click the Add Watch button. As an alternatice, in both MicrosoftVisual Basic versions, in the Watch window, double-click under the Name header, type either thename of the variable only or an expression that has the variable and an operation, then pressEnter.

After creating the desired entries in the Watch window, continue debugging. You will see the valuesbeing automatically updated in the Value column of the Watch window.

If you don't need a certain entry in the Watch window, you can remove it, or you can delete allentries in the window. To remove an entry, right-click it and click Delete Watch. To remove allentries, right-click anywhere in the Watch window and click Clear All.

Application: Using the Watch Window

1. To start debugging, on the main menu, click Debug -> Step Into

2. If the Watch window is not displaying:

and if you are using Microsoft Visual Basic 2010 Express, on the main menu, click

Page 437: Microsoft Visual Basic 2010 Tutorial

Debug -> Windows -> Watch.

If you are using Microsoft Visual Studio, on the Debug toolbar, click Watch 1 (if theDebug toolbar is not available, right-click the Standard toolbar and click Debug)Just in case, right-click inside the Watch window and click Clear All

3. In the Watch window, double-click under Name, type TimeWorked * 1.50 and press Enter(this will be used to evaluate overtime)

4. Still in the Watch window, click under TimeWorked * 1.50, type HourlySalary + 0.55 andpress Enter

5. Click under HourlySalary + 0.55, type TimeWorked * HourlySalary and press the downarrow key

6. Type (TimeWorked * HourlySalary) - TotalDeductions and press Enter

7. Make sure you have access to the Immediate window.Click inside the Immediate window

8. Type TimeWorked = 7.50 and press Enter

9. Observe the update in the Watch window

10. In the Immediate window, click the empty line, type HourlySalary = 18.24 and press Enter

11. Check the change in the Watch window

12. In the Immediate window, click the empty line, type TotalDeductions = 38.75 and pressEnter

13. See the result in the Watch window

14. Click the next empty line in the Immediate window

15. Press the up arrow key to see the previously entered lines until you get to TimeWorked.Change it to TimeWorked = 12.50 and press Enter

16. Press the up arrow key until HourlySalary = 18.24 is selected. Edit it to show HourlySalary =20.08 and press Enter

17. Press F8 or F11 continuously to the end

The IntelliTrace Window

While debugging, you are usually curious to know what line, section, or file is currently beingexamined:

To know the procedure inside of which the current execution is proceeding, you can look intothe Code Editor

To know the line whose code is executing, in the Code Editor, you can see a yellow right-pointing arrow on its margin

Since the lines of code are numbered, to know the number of the line of code that is currently

Page 438: Microsoft Visual Basic 2010 Tutorial

executing, you can look in the right section of the status bar with a label marked with Ln

If the project is using more than one file, to know the file whose code is currently executing,you can check the label that has focus in the top bar of the Code Editor

If you are using Microsoft Visual Studio 2010 Ultimate, to get all of this information in one group,you can use a window named IntelliTrace. To get the IntelliTrace window (in Microsoft VisualStudio 2010 Ultimate)

On the main menu, click Debug -> Windows -> IntelliTrace Events

On the main menu, click Debug -> Intellitrace -> IntelliTrace Events

Press Ctrl + Alt + Y, F

Application: Ending the Lesson

1. On the main menu, click File -> Close Solution (Microsoft Visual Studio) or File -> CloseProject (Microsoft Visual Basic 2010 Express)

2. When asked whether you want to save, click Discard

Home Copyright © 2010 FunctionX, Inc.

Page 439: Microsoft Visual Basic 2010 Tutorial

Error Handling

Error Handling

Overview

When using your application, a user may encounter various types of problems, some of whichcould come from you by some negligence when you worked on the project. Some other problemscould occur only at the time the application is being used. Some other problems could be causedby the computer on which the application is being used. While developing your application, youshould anticipate as many problems as possible as take appropriate actions.

Error Categories

There are three main types of errors that could occur while your application is being used:

1. Syntax Errors: A syntax error comes from your mistyping a word or forming a bad expressionin your code. It could be that you misspelled a keyword such as ByVel instead of ByVal. Itcould also be a bad expression. Examples are:

524+ + 62.55

if Number == 2 Number = 6

If you use the Microsoft Visual Basic IDE to write your code, it would point out the errors whileyou are writing your code, giving up time to fix them. There are other syntax errors that theIDE may not detect. This could come from using a data type or class that doesn't exist.

When you compile your application, the compiler can let you know about other syntax errors.Those types of errors are those the compiler cannot execute. It this case, the compilerintercepts, stops, and lets you know. For this reason, syntax errors are almost the easiest tofix. Most of the time, the compiler would point out where the problem is so you can fix it.

2. Run-Time Errors: After all syntax errors have been fixed, the program may be ready for theuser. The time period a person is using an application is called run-time. There are differenttypes of problems that a user may face when interacting with your program. For example,imagine that, in your code, you indicate that a picture would be loaded and displayed to theuser but you forget to ship the picture or the directory of the picture indicated in your codebecomes different when a user opens your application. In this case, when you compiled andexecuted the application in your machine, everything was fine. This is a type of run-time error.Run-time errors are mostly easy to fix because you will know what the problem is occurringand why.

3. Logic Errors: These are errors that don't fit in any of the above categories. They could becaused by the user misusing your application, a problem with the computer on which theapplication is running while the same application is working fine in another computer. Becauselogic errors can be vague, they can also be difficult to fix.

One of the best qualities of an effective programmer is to anticipate as many problems as possibleand to deal with them in the early stages. Some problems can be easy to fix. With some others,you will simply need more experience to know how to fix them. Unfortunately, it will not beunusual to have users asking you to fix your application when a problem may not come from it.

Error Handling

Introduction

Most or early errors occur in your code. If you are using the IDE to write your code, it can helpyou detect syntax errors and fix them. If you are using Notepad and the free vbc compiler as wehave done so far, you can start by paying attention to your code. When you think everything isfine, compile your code. If there is a syntax error, the compiler will let you know. If there is nosyntax error, the compilation will be over and the executable will be ready. You can then executethe application to see the result. If the user is not asked to provide value(s), you are less likely toget a run-time error.

A run-time error is one that occurs when using your application. Suppose you write the followingcode:

Module Exercise

Page 440: Microsoft Visual Basic 2010 Tutorial

Public Function Main() As Integer Dim Number As Double Dim Twice As Double

Console.Write("Enter a number: ") Number = Console.ReadLine() Twice = Number * 2

Console.WriteLine("{0} * 2 = {1}", Number, Twice) Console.WriteLine()

Return 0 End Function

End Module

Here is an example of executing it:

Enter a number: 246.88246.88 * 2 = 493.76

The first thing your should do is to imagine what could cause a problem. If you think there is sucha possibility, start by creating a label that could be used to transfer code if a problem occurs. Hereis an example:

Module Exercise

Public Function Main() As Integer Dim Number As Double Dim Twice As Double

Console.Write("Enter a number: ") Number = Console.ReadLine() Twice = Number * 2

Console.WriteLine("{0} * 2 = {1}", Number, Twice) Console.WriteLine()

ThereWasAProblem: Console.WriteLine("There was a problem when executing your instructions")

Return 0 End Function

End Module

As we saw when we introduced labels, if you create one, you should tell the compiler when tojump to that label. Otherwise, as in this case, the label section would always execute. Here is anexample of running the above version:

Enter a number: 12.4612.46 * 2 = 24.92

There was a problem when executing your instructions

In this case, we want the label section to execute only when we want it to. To prevent thecompiler from reaching this section if not directed so, you can add an Exit Sub line above thelabel section:

Module Exercise

Public Function Main() As Integer Dim Number As Double Dim Twice As Double

Console.Write("Enter a number: ") Number = Console.ReadLine() Twice = Number * 2

Console.WriteLine("{0} * 2 = {1}", Number, Twice) Console.WriteLine()

Exit Sub

ThereWasAProblem: Console.WriteLine("There was a problem when executing your instructions")

Return 0 End Function

End Module

This time if you execute the program with an appropriate value, the label section would not bereached.

In Case Of Error, Jump To Label

The above program will compile fine. When executing it, imagine that the user types aninappropriate value such as 24$.58 instead of 244.58. In this case, the value is not a number andthe program would "crash" and let you know that there was a problem. If you have someexperience, you would know what the problem was, otherwise, you would face a vagueexplanation. The short story is that the compiler couldn't continue because, in this case, it couldnot multiply 24$.58 by 2.

Page 441: Microsoft Visual Basic 2010 Tutorial

If a problem occurs when a person is using your program, the compiler may display a nasty andinsignificant message to the user who would not know what to do with it. Therefore, you can startby creating an appropriate label as introduced above. An error normally occurs in a procedure.Therefore, to make your code easier to read, you should create a label that shows that it is madefor an error instead of being a regular label. The label should also reflect the name of theprocedure. Here is an example:

Module Exercise

Public Function Main() As Integer Dim Number As Double Dim Twice As Double

Console.Write("Enter a number: ") Number = Console.ReadLine() Twice = Number * 2

Console.WriteLine("{0} * 2 = {1}", Number, Twice) Console.WriteLine()

Exit Sub

Err_Main: Console.WriteLine("In Main(): The operation could not be executed")

Return 0 End Function

End Module

When you think there will be a problem in your code, somewhere in the lines under the name ofthe procedure but before the line that could cause the problem, type On Error GoTo followed bythe name of the label that would deal with the error. Here is an example:

Module Exercise

Public Function Main() As Integer On Error GoTo Err_Main Dim Number As Double Dim Twice As Double

Console.Write("Enter a number: ") Number = Console.ReadLine() Twice = Number * 2

Console.WriteLine("{0} * 2 = {1}", Number, Twice) Console.WriteLine()

Exit Sub

Err_Main: Console.WriteLine("In Main(): The operation could not be executed")

Return 0 End Function

End Module

Here is an example of running the program:

Enter a number: 24$.58In Main(): The operation could not be executed

When the On Error GoTo statement is used, this indicates to the compiler that if any type oferror occurs while the code of this procedure is executed, it should transfer the compilation to thelabel. In this case, as soon as something bad happens, the compiler marks the area where theproblem occurred, skips the normal code and jumps to the label indicated by the On Error GoToline. After the section of that label is executed, the compiler returns where the error occurred. Ifthere is nothing to solve the problem, the compiler continues down but without executing the linesof code involved. In this case, it would encounter the Exit Sub line and get out of the procedure.

In Case Of Error, Jump To Line #

Although the label is more explicit, it only indicates to the compiler what line to jump to in case ofa problem. The alternative is to specify a numbered label instead of a lettered label. Here is anexample:

Module Exercise

Public Function Main() As Integer On Error GoTo 624 Dim Number As Double Dim Twice As Double

Console.Write("Enter a number: ") Number = Console.ReadLine() Twice = Number * 2

Console.WriteLine("{0} * 2 = {1}", Number, Twice) Console.WriteLine()

Page 442: Microsoft Visual Basic 2010 Tutorial

Exit Function

624: Console.WriteLine("In Main(): The operation could not be executed")

Return 0 End Function

End Module

Here is an example of running the program:

Enter a number: 25GIn Main(): The operation could not be executedPress any key to continue . . .

Resume

If a problem occurs in your code and you provide a label to display a friendly message as doneabove, the compiler would display the message and exit from the procedure. If this happens, asmentioned above, when the compiler returns where the problem occurred, you can provide analternate. For example, in our program, if the user provides an inappropriate value that causes theerror, you can provide an alternate value and ask the compiler to continue as if nothing happened.In this case, you want to compiler to "resume" its activity.

To indicate that the program should continue, you can use the Resume keyword. Here is anexample:

Module Exercise

Public Function Main() As Integer On Error GoTo Err_Main Dim Number As Double Dim Twice As Double

Console.Write("Enter a number: ") Number = Console.ReadLine()

Resume

Twice = Number * 2

Console.WriteLine("{0} * 2 = {1}", Number, Twice) Console.WriteLine()

Exit Sub

Err_Main: Console.WriteLine("In Main(): The operation could not be executed")

Return 0 End Function

End Module

When an error occurs, if you want the program to continue with with an alternate value than theone that caused the problem, in the label section, type Resume Next. Here is an example:

Module Exercise

Public Function Main() As Integer On Error GoTo Err_Main Dim Number As Double Dim Twice As Double

Console.Write("Enter a number: ") Number = Console.ReadLine()

Resume

Twice = Number * 2

Console.WriteLine("{0} * 2 = {1}", Number, Twice) Console.WriteLine()

Exit Sub

Err_Main: Console.WriteLine("In Main(): The operation could not be executed") Resume Next

Return 0 End Function

End Module

In this case, since any numeric variable is initialized with 0, when the compiler returns to the lineof code that caused the problem, it would use 0 as a substitute to the inappropriate value. Here isan example of running the above program:

Enter a number: 24$.58In Main(): The operation could not be executed0 * 2 = 0

Page 443: Microsoft Visual Basic 2010 Tutorial

Based on this, you can provide a new value to use in case of error. Here is an example:

Module Exercise

Public Function Main() As Integer On Error GoTo Err_Main Dim Number As Double Dim Twice As Double

Console.Write("Enter a number: ") Number = Console.ReadLine()

Twice = Number * 2

Console.WriteLine("{0} * 2 = {1}", Number, Twice) Console.WriteLine()

Exit Sub

Err_Main: Console.WriteLine("Invalid Number: The value you provided is inappropriate") Console.WriteLine("10 will be used instead") Number = 10 Resume Next

Return 0 End Function

End Module

Here is one example of running the program:

Enter a number: 244.58244.58 * 2 = 489.16

Here is another example of running the same program:

Enter a number: 24$.58Invalid Number: The value you provided is inappropriate10 will be used instead10 * 2 = 20

The Err Object

To support error handling, Visual Basic provides a global variable named Err. This allows you toidentify the error and its description. Because an error depends on what caused it and why, thevalues of the Err variable also depend and are not always the same.

Home Copyright © 2005-2009 FunctionX, Inc.

Page 444: Microsoft Visual Basic 2010 Tutorial

Introduction to Exception Handling

Introduction

As opposed to error handling techniques used to deal with a program's problems, the VisualBasic language now supports a technique referred to as exception handling. This technique wasmostly used by other languages such as C/C++, Object Pascal, C#, etc. This technique is alsoreferred to as structured exception handling (SEH).

Practical Learning: Introducing Exception Handling

1. Start Microsoft Visual Studio and create a Console Application named GDCS4

2. To create a new structure, on the main menu, click Project -> Add New Item...

3. In the Templates list, click Code File

4. Set the Name to OrderInfo

5. Click Add

6. In the document, type the following: Public Structure OrderInformation ' Basic information about an order Public CustomerName As String Public HomePhone As String Public OrderDate As DateTime Public OrderTime As DateTime Public NumberOfShirts As Integer Public NumberOfPants As Integer Public NumberOfDresses As IntegerEnd Structure

7. To create a new file, on the main menu, click Project -> Add Class...

8. Set the Name to OrderProcessing

9. Click Add

10. Change the document as follows: Public Class OrderProcessing ' Price of items ReadOnly PriceOneShirt As Double = 0.95 ReadOnly PriceAPairOfPants As Double = 2.95 ReadOnly PriceOneDress As Double = 4.55 ReadOnly TaxRate As Double = 0.0575 ' 5.75%

Dim order As OrderInformation

' Each of these sub totals will be used for cleaning items Private SubTotalShirts As Double Private SubTotalPants As Double Private SubTotalDresses As Double

' Values used to process an order Private TotalOrder As Double Private TaxAmount As Double Private SalesTotal As Double Private AmountTended As Double Private Difference As Double

Public Sub ProcessOrder() Console.WriteLine("-/- Georgetown Cleaning Services -/-") ' Request order information from the user Console.Write("Enter Customer Name: ") Order.CustomerName = Console.ReadLine() Console.Write("Enter Customer Phone: ") Order.HomePhone = Console.ReadLine() Console.Write("Enter the order date(mm/dd/yyyy): ") Order.OrderDate = DateTime.Parse(Console.ReadLine()) Console.Write("Enter the order time(hh:mm AM/PM): ") Order.OrderTime = DateTime.Parse(Console.ReadLine())

' Request the quantity of each category of items Console.Write("Number of Shirts: ") order.NumberOfShirts = CInt(Console.ReadLine())

Console.Write("Number of Pants: ") order.NumberOfPants = CInt(Console.ReadLine())

Console.Write("Number of Dresses: ") order.NumberOfDresses = CInt(Console.ReadLine())

' Perform the necessary calculations SubTotalShirts = Order.NumberOfShirts * PriceOneShirt

Page 445: Microsoft Visual Basic 2010 Tutorial

SubTotalPants = Order.NumberOfPants * PriceAPairOfPants SubTotalDresses = Order.NumberOfDresses * PriceOneDress ' Calculate the "temporary" total of the order TotalOrder = SubTotalShirts + SubTotalPants + SubTotalDresses

' Calculate the tax amount using a constant rate TaxAmount = TotalOrder * TaxRate ' Add the tax amount to the total order SalesTotal = TotalOrder + TaxAmount

' Communicate the total to the user... Console.WriteLine(vbcrlf & "The Total order is: {0:C}", SalesTotal) ' and request money for the order Console.Write("Amount Tended? ") AmountTended = Decimal.Parse(Console.ReadLine())

' Calculate the difference owed to the customer ' or that the customer still owes to the store Difference = AmountTended - SalesTotal

ShowReceipt() End Sub

Private Sub ShowReceipt() Console.WriteLine() ' Display the receipt Console.WriteLine("====================================") Console.WriteLine("-/- Georgetown Cleaning Services -/-") Console.WriteLine("====================================") Console.WriteLine("Customer: {0}", Order.CustomerName) Console.WriteLine("Home Phone: {0}", Order.HomePhone) Console.WriteLine("Order Date: {0:D}", Order.OrderDate) Console.WriteLine("Order Time: {0:t}", Order.OrderTime) Console.WriteLine("------------------------------------") Console.WriteLine("Item Type Qty Unit/Price Sub-Total") Console.WriteLine("------------------------------------") Console.WriteLine("Shirts {0,3} {1,4} {2,6}", _ order.NumberOfShirts, PriceOneShirt, SubTotalShirts) Console.WriteLine("Pants {0,3} {1,4} {2,6}", _ order.NumberOfPants, PriceAPairOfPants, SubTotalPants) Console.WriteLine("Dresses {0,3} {1,4} {2,6}", _ order.NumberOfDresses, PriceOneDress, SubTotalDresses) Console.WriteLine("------------------------------------") Console.WriteLine("Total Order: {0,6}", TotalOrder.ToString("C")) Console.WriteLine("Tax Rate: {0,6}", TaxRate.ToString("P")) Console.WriteLine("Tax Amount: {0,6}", TaxAmount.ToString("C")) Console.WriteLine("Net Price: {0,6}", SalesTotal.ToString("C")) Console.WriteLine("------------------------------------") Console.WriteLine("Amount Tended: {0,6}", AmountTended.ToString("C")) Console.WriteLine("Difference: {0,6}", Difference.ToString("C")) Console.WriteLine("====================================") End SubEnd Class

11. In the Solution Explorer, right-click Module1.vb and click Rename

12. Type GeorgetownDryCleaningServices.vb and press Enter.If asked whether you want to rename the file, click Yes

13. In the Solution Explorer, double-click GeorgetownDryCleaningServices.vb

14. Change the file as follows: Module GeorgetownDryCleaningServices

Public Function Main() As Integer Dim Order As OrderProcessing = New OrderProcessing

Order.ProcessOrder()

Return 0 End Function

End Module

15. Press Ctrl + F5 to execute the application. Here is an example: -/- Georgetown Cleaning Services -/-Enter Customer Name: Judith PearsonEnter Customer Phone: (301) 884-0912Enter the order date(mm/dd/yyyy): 10/05/2009Enter the order time(hh:mm AM/PM): 08:12Number of Shirts: 6Number of Pants: 4Number of Dresses: 1

The Total order is: $23.32Amount Tended? 25

====================================-/- Georgetown Cleaning Services -/-====================================Customer: Judith PearsonHome Phone: (301) 884-0912Order Date: Monday, October 05, 2009Order Time: 8:12 AM------------------------------------Item Type Qty Unit/Price Sub-Total

Page 446: Microsoft Visual Basic 2010 Tutorial

------------------------------------Shirts 6 0.95 5.7Pants 4 2.95 11.8Dresses 1 4.55 4.55------------------------------------Total Order: $22.05Tax Rate: 5.75 %Tax Amount: $1.27Net Price: $23.32------------------------------------Amount Tended: $25.00Difference: $1.68====================================Press any key to continue . . .

16. Close the DOS window and return to your programming environment

Try to Catch the Error

As mentioned already, errors are likely going to occur in your program. The more you anticipatethem and take action, the better your application will be. We have already seen that syntax errorsare usually human mistakes such as misspelling, bad formulation of expressions, etc. The compilerwill usually help you fix the problem by pointing it out.

SEH is based on two main keywords: Try and Catch. An exception handling section starts with theTry keyword and stops with the End Try statement. Between Try and End Try, there must by atleast one Catch section. Therefore, exception handling uses the following formula:

Try

Catch End Try

Exception handling always starts with the Try keyword. Under the Try line, write the normal codethat the compiler must execute. Here is an example:

Module Exercise

Public Function Main() As Integer Dim Number As Double Dim Twice As Double Try Console.Write("Enter a number: ") Number = Console.ReadLine()

Twice = Number * 2

Console.WriteLine("{0} * 2 = {1}", Number, Twice) Console.WriteLine() End Try

Return 0 Exit Function

End Module

As the compiler is treating code in the Try section, if it encounters a problem, it "gets out" of theTry section and starts looking for a Catch section. Therefore, you must always have a Catchsection. If you don't, as seen on the above code, the program will not compile. A Catch sectionmust be written before the End Try line:

Module Exercise

Public Function Main() As Integer Dim Number As Double Dim Twice As Double Try Console.Write("Enter a number: ") Number = Console.ReadLine()

Twice = Number * 2

Console.WriteLine("{0} * 2 = {1}", Number, Twice) Console.WriteLine() Catch

End Try

Return 0 Exit Function

End Module

When the Catch keyword is simply written as above, it would be asked to treat any error thatoccurs. For example, here is one example of executing the above program:

Enter a number: 244.58244.58 * 2 = 489.16

Here is another example of executing the same program:

Enter a number: 24$.58

Page 447: Microsoft Visual Basic 2010 Tutorial

Notice that the program stops if there is any type of problem but in this case, it doesn't bother tolet the user know why there is no result displayed. Because there can be various types of errors ina program, you also should make your program more intuitive and friendlier so that, when aproblem occurs, the user would know the type of problem. This is also useful if somebody callsyou and says that your program is not functioning right. If there is a way the user can tell whatexact type of error is displaying, may be you would find the solution faster.

Practical Learning: Trying Exceptions

1. To introduce exceptions, access the OrderProcessing.vb file and change it as follows: Public Class OrderProcessing . . . No Change

Public Sub ProcessOrder() Console.WriteLine("-/- Georgetown Cleaning Services -/-") ' Request order information from the user . . . No Change

' Request the quantity of each category of items Try Console.Write("Number of Shirts: ") order.NumberOfShirts = CInt(Console.ReadLine()) Catch

End Try

Try Console.Write("Number of Pants: ") order.NumberOfPants = CInt(Console.ReadLine()) Catch

End Try

Try Console.Write("Number of Dresses: ") order.NumberOfDresses = CInt(Console.ReadLine()) Catch

End Try

. . . No Change

End Sub

Private Sub ShowReceipt() . . . No Change

End SubEnd Class

2. Save the file

Exceptions and Custom Messages

As mentioned already, if an error occurs when processing the program in the try section, the compilertransfer the processing to the next catch section. You can then use the catch section to deal with theerror. At a minimum, you can display a message to inform the user. Here is an example:

Public Class Exercise Public Function Main() As Integer Dim Number As Double

Try Console.Write("Type a number: ") Number = cdbl(Console.ReadLine())

Console.WriteLine(vbcrlf & "{0} * 2 = {1}", Number, Number * 2) Catch Console.WriteLine("There was a problem with the program") End Try

Return 0 Exit FunctionEnd Class

Of course, this type of message is not particularly clear but this time, the program will not crash.

Practical Learning: Displaying Custom Messages

1. To display custom messages to the user, change the OrderProcess.vb file as follows: Public Class OrderProcessing

. . . No Change

Page 448: Microsoft Visual Basic 2010 Tutorial

Public Sub ProcessOrder() . . . No Change

' Request the quantity of each category of items Try Console.Write("Number of Shirts: ") order.NumberOfShirts = CInt(Console.ReadLine()) Catch Console.WriteLine("The value you typed for the number of " & _ "shirts is not a valid number") End Try

Try Console.Write("Number of Pants: ") order.NumberOfPants = CInt(Console.ReadLine()) Catch Console.WriteLine("The value you typed for the number of " & _ "pair or pants is not a valid number") End Try

Try Console.Write("Number of Dresses: ") order.NumberOfDresses = CInt(Console.ReadLine()) Catch Console.WriteLine("The value you typed for the number of " & _ "dresses is not a valid number") End Try

' Perform the necessary calculations SubTotalShirts = order.NumberOfShirts * PriceOneShirt SubTotalPants = order.NumberOfPants * PriceAPairOfPants SubTotalDresses = order.NumberOfDresses * PriceOneDress ' Calculate the "temporary" total of the order TotalOrder = SubTotalShirts + SubTotalPants + SubTotalDresses

' Calculate the tax amount using a constant rate TaxAmount = TotalOrder * TaxRate ' Add the tax amount to the total order SalesTotal = TotalOrder + TaxAmount

' Communicate the total to the user... Console.WriteLine(vbCrLf & "The Total order is: {0:C}", SalesTotal) ' and request money for the order Try Console.Write("Amount Tended? ") AmountTended = CDbl(Console.ReadLine()) Catch Console.WriteLine( _ "You were asked to enter an amount of money but...") End Try

' Calculate the difference owed to the customer ' or that the customer still owes to the store Difference = AmountTended - SalesTotal

ShowReceipt() End Sub

Private Sub ShowReceipt() . . . No Change End SubEnd Class

2. Execute the application and enter the values when prompted. Here is an example: -/- Georgetown Cleaning Services -/-Enter Customer Name: AlexandriaEnter Customer Phone: (102) 797-8382Enter the order date(mm/dd/yyyy): 04/02/2001Enter the order time(hh:mm AM/PM): 09:22 AMNumber of Shirts: 6Number of Pants: WThe value you typed for the number of pair or pants is not a valid numberNumber of Dresses: 5

The Total order is: $30.09Amount Tended? _100DYou were asked to enter an amount of money but...

====================================-/- Georgetown Cleaning Services -/-====================================Customer: AlexandriaHome Phone: (102) 797-8382Order Date: Monday, April 02, 2001Order Time: 9:22 AM------------------------------------Item Type Qty Unit/Price Sub-Total------------------------------------Shirts 6 0.95 5.70Pants 0 2.95 0Dresses 5 4.55 22.75------------------------------------Total Order: $28.45Tax Rate: 5.75 %Tax Amount: $1.64Net Price: $30.09------------------------------------

Page 449: Microsoft Visual Basic 2010 Tutorial

Amount Tended: $0.00Difference: ($30.09)====================================

3. Close the DOS window and return to your programming environment

Home Copyright © 2005-2009 FunctionX, Inc.

Page 450: Microsoft Visual Basic 2010 Tutorial

.NET Support for Exception Handling

Exceptions in the .NET Framework

The Exception Class

The .NET Framework provides a high level of support for exception handling, and the Visual Basiclanguage uses it. To support exception handling, the .NET Framework provides the Exceptionclass. Once the compiler encounters an error, the Exception class allows you to identify the typeof error and take appropriate action(s).

Normally, Exception mostly serves as the general class of exceptions. Anticipating various typesof problems that can occur in a program, Microsoft derived various classes from Exception tomake this issue friendlier. As a result, almost any type of exception you may encounter already hasa class created to deal with it. Therefore, when your program faces an exception, you can easilyaccess the class appropriate for that error. There are so many exception classes that we cannotstudy or review them all. The solution we will use is to introduce or review a class when we meetits type of error.

Practical Learning: Introducing Exception Handling

1. Start Microsoft Visual Studio and create a Console Application named GDCS5

2. To create a new structure, on the main menu, click Project -> Add New Item...

3. In the Templates list, click Code File

4. Set the Name to OrderInfo

5. Click Add

6. In the document, type the following: Public Structure OrderInformation ' Basic information about an order Public CustomerName As String Public HomePhone As String Public OrderDate As DateTime Public OrderTime As DateTime Public NumberOfShirts As Integer Public NumberOfPants As Integer Public NumberOfDresses As IntegerEnd Structure

7. To create a new file, on the main menu, click Project -> Add Class...

8. Set the Name to OrderProcessing

9. Click Add

10. Change the document as follows: Public Class OrderProcessing ' Price of items ReadOnly PriceOneShirt As Double = 0.95 ReadOnly PriceAPairOfPants As Double = 2.95 ReadOnly PriceOneDress As Double = 4.55 ReadOnly TaxRate As Double = 0.0575 ' 5.75%

Dim order As OrderInformation

' Each of these sub totals will be used for cleaning items Private SubTotalShirts As Double Private SubTotalPants As Double Private SubTotalDresses As Double

' Values used to process an order Private TotalOrder As Double Private TaxAmount As Double Private SalesTotal As Double Private AmountTended As Double Private Difference As Double

Public Sub ProcessOrder() Console.WriteLine("-/- Georgetown Cleaning Services -/-") ' Request order information from the user Console.Write("Enter Customer Name: ") Order.CustomerName = Console.ReadLine() Console.Write("Enter Customer Phone: ") Order.HomePhone = Console.ReadLine() Console.Write("Enter the order date(mm/dd/yyyy): ") Order.OrderDate = DateTime.Parse(Console.ReadLine()) Console.Write("Enter the order time(hh:mm AM/PM): ") Order.OrderTime = DateTime.Parse(Console.ReadLine())

Page 451: Microsoft Visual Basic 2010 Tutorial

' Request the quantity of each category of items Try Console.Write("Number of Shirts: ") order.NumberOfShirts = CInt(Console.ReadLine()) Catch Console.WriteLine("The value you typed for the number of " & _ "shirts is not a valid number") End Try

Try Console.Write("Number of Pants: ") order.NumberOfPants = CInt(Console.ReadLine()) Catch Console.WriteLine("The value you typed for the number of " & _ "pair or pants is not a valid number") End Try

Try Console.Write("Number of Dresses: ") order.NumberOfDresses = CInt(Console.ReadLine()) Catch Console.WriteLine("The value you typed for the number of " & _ "dresses is not a valid number") End Try

' Perform the necessary calculations SubTotalShirts = order.NumberOfShirts * PriceOneShirt SubTotalPants = order.NumberOfPants * PriceAPairOfPants SubTotalDresses = order.NumberOfDresses * PriceOneDress ' Calculate the "temporary" total of the order TotalOrder = SubTotalShirts + SubTotalPants + SubTotalDresses

' Calculate the tax amount using a constant rate TaxAmount = TotalOrder * TaxRate ' Add the tax amount to the total order SalesTotal = TotalOrder + TaxAmount

' Communicate the total to the user... Console.WriteLine(vbCrLf & "The Total order is: {0:C}", SalesTotal) ' and request money for the order Try Console.Write("Amount Tended? ") AmountTended = Decimal.Parse(Console.ReadLine()) Catch Console.WriteLine( _ "You were asked to enter an amount of money but...") End Try

' Calculate the difference owed to the customer ' or that the customer still owes to the store Difference = AmountTended - SalesTotal

ShowReceipt() End Sub

Private Sub ShowReceipt() Console.WriteLine() ' Display the receipt Console.WriteLine("====================================") Console.WriteLine("-/- Georgetown Cleaning Services -/-") Console.WriteLine("====================================") Console.WriteLine("Customer: {0}", Order.CustomerName) Console.WriteLine("Home Phone: {0}", Order.HomePhone) Console.WriteLine("Order Date: {0:D}", Order.OrderDate) Console.WriteLine("Order Time: {0:t}", Order.OrderTime) Console.WriteLine("------------------------------------") Console.WriteLine("Item Type Qty Unit/Price Sub-Total") Console.WriteLine("------------------------------------") Console.WriteLine("Shirts {0,3} {1,4} {2,6}", _ order.NumberOfShirts, PriceOneShirt, SubTotalShirts) Console.WriteLine("Pants {0,3} {1,4} {2,6}", _ order.NumberOfPants, PriceAPairOfPants, SubTotalPants) Console.WriteLine("Dresses {0,3} {1,4} {2,6}", _ order.NumberOfDresses, PriceOneDress, SubTotalDresses) Console.WriteLine("------------------------------------") Console.WriteLine("Total Order: {0,6}", TotalOrder.ToString("C")) Console.WriteLine("Tax Rate: {0,6}", TaxRate.ToString("P")) Console.WriteLine("Tax Amount: {0,6}", TaxAmount.ToString("C")) Console.WriteLine("Net Price: {0,6}", SalesTotal.ToString("C")) Console.WriteLine("------------------------------------") Console.WriteLine("Amount Tended: {0,6}", AmountTended.ToString("C")) Console.WriteLine("Difference: {0,6}", Difference.ToString("C")) Console.WriteLine("====================================") End SubEnd Class

11. In the Solution Explorer, right-click Module1.vb and click Rename

12. Type GeorgetownDryCleaningServices.vb and press Enter.If asked whether you want to rename the file, click Yes

13. In the Solution Explorer, double-click GeorgetownDryCleaningServices.vb

14. Change the file as follows: Module GeorgetownDryCleaningServices

Public Function Main() As Integer Dim Order As OrderProcessing = New OrderProcessing

Page 452: Microsoft Visual Basic 2010 Tutorial

Order.ProcessOrder()

Return 0 End Function

End Module

15. Press Ctrl + F5 to execute the application. Here is an example: -/- Georgetown Cleaning Services -/-Enter Customer Name: Judith PearsonEnter Customer Phone: (301) 884-0912Enter the order date(mm/dd/yyyy): 10/05/2009Enter the order time(hh:mm AM/PM): 08:12Number of Shirts: 6Number of Pants: 4Number of Dresses: 1

The Total order is: $23.32Amount Tended? 25

====================================-/- Georgetown Cleaning Services -/-====================================Customer: Judith PearsonHome Phone: (301) 884-0912Order Date: Monday, October 05, 2009Order Time: 8:12 AM------------------------------------Item Type Qty Unit/Price Sub-Total------------------------------------Shirts 6 0.95 5.7Pants 4 2.95 11.8Dresses 1 4.55 4.55------------------------------------Total Order: $22.05Tax Rate: 5.75 %Tax Amount: $1.27Net Price: $23.32------------------------------------Amount Tended: $25.00Difference: $1.68====================================Press any key to continue . . .

16. Close the DOS window and return to your programming environment

The Exception's Message

In exception handling, errors are dealt with in the Catch section. On the right side of Catch,behave as if you were declaring a variable of the type of exception you want to deal with. Bydefault, an exception is first of type Exception. Based on this, a typical formula to implementexception handling is:

Try ' Process the normal flow of the program hereCatch Parameter As Exception ' Deal with the exception hereEnd Try

When an exception occurs in the Try section, code compilation is transferred to the Catch section.If you declare the exception as an Exception type, this class will identify the error. One of theproperties of the Exception class is called Message. This property contains a string that describesthe type of error that occurred. You can then use this Exception.Message property to display anerror message if you want. Here is an example:

Public Class Exercise Public Function Main() As Integer Dim Number As Double

Try Console.Write("Type a number: ") Number = CDbl(Console.ReadLine())

Console.WriteLine(vbcrlf & "{0} * 2 = {1}", Number, Number * 2) Catch ex As Exception Console.WriteLine(ex.Message) End Try

Return 0 End SubEnd Class

Here is an example of running the program:

Type a number: 45KP2Cast from string "45KP2" to type 'Double' is not valid.

Custom Error Messages

As you can see, one of the strengths of the Exception.Message property is that it gives you agood indication of the type of problem that occurred. Sometimes, the message provided by the

Page 453: Microsoft Visual Basic 2010 Tutorial

Exception class may not appear explicit enough. In fact, you may not want to show it to the usersince, as in this case, the user may not understand what the word "Cast" in this context meansand why it is being used. As an alternative, you can create your own message and display it to theuser. Here is an example:

Public Class Exercise Public Function Main() As Integer Dim Number As Double

Try Console.Write("Type a number: ") Number = CDbl(Console.ReadLine())

Console.WriteLine(vbcrlf & "{0} * 2 = {1}", Number, Number * 2) Catch ex As Exception Console.WriteLine("The operation could not be carried because " & _ "the number you typed is not valid") End Try

Return 0 End SubEnd Class

Here is an example of running the program:

Type a number: 88D.46The operation could not be carried because the number you typed is not valid

You can also combine the Exception.Message message and your own message:

Public Class Exercise Public Function Main() As Integer Dim Number As Double

Try Console.Write("Type a number: ") Number = CDbl(Console.ReadLine())

Console.WriteLine(vbcrlf & "{0} * 2 = {1}", Number, Number * 2) Catch ex As Exception Console.WriteLine(ex.Message & vbCrLf & _ "The operation could not be carried because " & _ "the number you typed is not valid") End Try

Return 0 End SubEnd Class

Here is an example of running the program:

Type a number: 45PK12Cast from string "45PK12" to type 'Double' is not valid.The operation could not be carried because the number you typed is not valid

A Review of .NET Exception Classes

Introduction

The .NET Framework provides various classes to handle almost any type of exception you can thinkof. There are so many of these classes that we can only mention the few that we regularly use inour application.

There are two main ways you can use one of the classes of the .NET Framework. If you know forsure that a particular exception will be produced, pass its name to the Catch clause and display acustom message. The second option you have consists of using the throw keyword. We will studyit later.

From now on, we will try to always indicate the type of exception that could be thrown ifsomething goes wrong in a program

InvalidCastException

When studying data formatting in Lesson 5, we saw that everything the user types into anapplication using the keyboard is primarily a string and that you must convert it to the appropriatetype before using it. When you request a specific type of value from the user, after the user hastyped it and you decide to convert it to the appropriate type using one of the built-in conversionfunctions (CDbl(), CInt, CDate, CSng, CDec, etc), if your conversion fails, the program produces(in the next lessons, we will use he word "throw") an error. The error is from theInvalidCastException class.

Here is a program that deals with a InvalidCastException exception:

Public Class Exercise Public Function Main() As Integer Dim Number As Double

Try

Page 454: Microsoft Visual Basic 2010 Tutorial

Console.Write("Type a number: ") Number = CDbl(Console.ReadLine())

Console.WriteLine("\n{0} * 2 = {1}", Number, Number * 2) Catch ex As InvalidCastException Console.WriteLine("You typed an invalid number") End Try

Return 0 End SubEnd Class

Here is an example of running the program:

Type a number: 39W.68gYou typed an invalid number

Practical Learning: Using the InvalidCastException Class

1. Change the OrderProcessing.vb file as follows: Public Class OrderProcessing . . . No Change

Public Sub ProcessOrder() . . . No Change

' Request the quantity of each category of items Try Console.Write("Number of Shirts: ") order.NumberOfShirts = CInt(Console.ReadLine()) Catch exc As InvalidCastException Console.WriteLine("The value you typed for the number of " & _ "shirts is not a valid number") End Try

Try Console.Write("Number of Pants: ") order.NumberOfPants = CInt(Console.ReadLine()) Catch exc As InvalidCastException Console.WriteLine("The value you typed for the number of " & _ "pair or pants is not a valid number") End Try

Try Console.Write("Number of Dresses: ") order.NumberOfDresses = CInt(Console.ReadLine()) Catch exc As InvalidCastException Console.WriteLine("The value you typed for the number of " & _ "dresses is not a valid number") End Try

' Perform the necessary calculations SubTotalShirts = order.NumberOfShirts * PriceOneShirt SubTotalPants = order.NumberOfPants * PriceAPairOfPants SubTotalDresses = order.NumberOfDresses * PriceOneDress ' Calculate the "temporary" total of the order TotalOrder = SubTotalShirts + SubTotalPants + SubTotalDresses

' Calculate the tax amount using a constant rate TaxAmount = TotalOrder * TaxRate ' Add the tax amount to the total order SalesTotal = TotalOrder + TaxAmount

' Communicate the total to the user... Console.WriteLine(vbCrLf & "The Total order is: {0:C}", SalesTotal) ' and request money for the order Try Console.Write("Amount Tended? ") AmountTended = CDbl(Console.ReadLine()) Catch exc As InvalidCastException Console.WriteLine("You were asked to enter " & _ "an amount of money but...") End Try

' Calculate the difference owed to the customer ' or that the customer still owes to the store Difference = AmountTended - SalesTotal

ShowReceipt() End Sub

Private Sub ShowReceipt() . . . No Change End SubEnd Class

2. Execute the application and enter the values when requested

3. Close the DOS window and return to your programming environment

The OverflowException Exception

Page 455: Microsoft Visual Basic 2010 Tutorial

A computer application receives, processes, and produces values on a regular basis as the programis running. To better manage these values, as we saw when studying variables and data types inLesson 2, the compiler uses appropriate amounts of space to store its values. It is not unusualthat either you the programmer or a user of your application provide a value that is beyond theallowed range of the data type. For example, a byte uses 8 bits to store a value and acombination of 8 bits can store a number no more than 255. If you provide a value higher than255 to be stored in a byte, you get an error. Consider the following program:

Public Class Exercise Public Function Main() As Integer Dim NumberOfPages As Byte

Console.Write("Enter the number of pages of the newspaper: ") NumberOfPages = CByte(Console.ReadLine())

Console.WriteLine("Number of Pages of the Newspaper: {0}", NumberOfPages) Return 0 End SubEnd Class

When a value beyond the allowable range is asked to be stored in memory, the compiler produces(or "throws") an error of the OverflowException class. Here is an example of running theprogram:

Enter the number of pages of the newspaper: 462

Unhandled Exception: System.OverflowException: Arithmetic operation resulted inan overflow. at Microsoft.VisualBasic.CompilerServices.ByteType.FromString(String Value) at Project5.Exercise.main() in C:\Programs\MSVB .NET 2003\Project5\Exercise.vb:line 8

As with the other errors, when this exception is thrown, you should take appropriate action.

FormatException

Once again, when studying the techniques of converting or formatting values in Lesson 5, we sawthat a value is passed to a conversion function for analysis. For a primitive data type, theconversion function scans the string and if the string cannot be converted into a valid character ornumber, the compiler usually throws an InvalidCastException exception as we saw above. Otherdata types such as Date also use use this technique to scan the value submitted to it. Forexample, if you request a date value from the user, the CDate() function scans the string tovalidate it. In US English, CDate() expects the user to type a string in the form m/d/yy ormm/dd/yy or mm/dd/yyyy or yyyy/mm/dd. Consider the following program:

Public Class Exercise Public Function Main() As Integer Dim DateHired As Date

Console.Write("Enter Date Hired: ") DateHired = DateTime.Parse(Console.ReadLine())

Console.WriteLine("Date Hired: {0:d}", DateHired) Return 0 End SubEnd Class

If the user types a value that cannot be converted into a valid date, the compiler throws anFormatException exception. Here is an example of running the above program:

Enter Date Hired: 04/12/2002Date Hired: 4/12/2002

Here is another example of running the program:

Enter Date Hired: 1998/10/24Date Hired: 10/24/1998

Here is one more example of running the program:

Enter Date Hired: 16/04/2002

Unhandled Exception: System.FormatException: String was not recognized as a valid DateTime. at System.DateTimeParse.GetDayOfNNY(DateTimeResult result, DateTimeRawInfo raw, DateTimeFormatInfo dtfi) at System.DateTimeParse.ProcessTerminaltState(Int32 dps, DateTimeResult result, DateTimeRawInfo raw, DateTimeFormatInfo dtfi) at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles) at System.DateTime.Parse(String s, IFormatProvider provider, DateTimeStyles styles) at System.DateTime.Parse(String s, IFormatProvider provider) at System.DateTime.Parse(String s) at Project5.Exercise.main() in C:\Programs\MSVB .NET 2003\Project5\Exercise.vb:line 8

One way you can avoid this is to guide the user about the type of expected value. Here is anexample:

Page 456: Microsoft Visual Basic 2010 Tutorial

Public Class Exercise Public Function Main() As Integer Dim DateHired As Date

Console.Write("Enter Date Hired (mm/dd/yyyy): ") DateHired = DateTime.Parse(Console.ReadLine())

Console.WriteLine("Date Hired: {0:d}", DateHired) Return 0 End SubEnd Class

You should still prepare to take appropriate actions, just in case this error is thrown.

The DivideByZeroException Exception

Division by zero is an operation to always avoid. It is so important that it is one of the mostfundamental exceptions of the computer. It is addressed at the core level even by the Intel andAMD processors. It is also addressed by the operating systems at their level. It is also addressedby most, if not all, compilers. It is also addressed by most, if not, all libraries. This means that thisexception is never welcomed anywhere. The .NET Framework also provides it own class to face thisoperation.

If an attempt to divide a value by 0, the compiler throws a DivideByZeroException exception.We will see an example later.

Techniques of Using Exceptions

Throwing an Exception

As mentioned above, the Exception class is equipped with a Message property that carries amessage for the error that occurred. We also mentioned that the message of this property maynot be particularly useful to a user. Fortunately, you can create your own message and pass it tothe Exception. To be able to receive custom messages, the Exception class provides the followingconstructor:

public Exception(string message)

To use it, in the section that you are anticipating the error, type the throw keyword followed by anew instance of the Exception class using the constructor that takes a string. Here is an example:

Public Class Exercise Public Function Main() As Integer Dim Number1 As Double, Number2 As Double Dim Operator As String Dim Result As Double

Try Console.Write("Enter First Number: ") Number1 = CDbl(Console.ReadLine()) Console.Write("Enter Operation (+, -, *, or /): ") Operator = CStr(Console.ReadLine()) Console.Write("Enter Second Number: ") Number2 = CDbl(Console.ReadLine())

If Operator = "+" Then Result = Number1 + Number2 ElseIf Operator = "-" Then Result = Number1 - Number2 ElseIf Operator = "*" Then Result = Number1 * Number2 ElseIf Operator = "/" Then Result = Number1 / Number2 Else Result = 0 End If

Console.WriteLine(vbCrLf & "{0} {1} {2} = {3}", _ Number1, Operator, Number2, Result) Catch ex as Exception Console.WriteLine( _ "Somewhere went wrong: your operation could not be performed") End Try

Return 0 End SubEnd Class

Here is an example of running the program:

Enter First Number: 244.98Enter Operation (+, -, *, or /): *Enter Second Number: 24.52

244.98 * 24.52 = 6006.9096

Here is another example of running the program:

Page 457: Microsoft Visual Basic 2010 Tutorial

Enter First Number: 405.66Enter Operation (+, -, *, or /): -Enter Second Number: 24GDSomething went wrong: your operation could not be performed

Here is one more example of running the program:

Enter First Number: 248.12Enter Operation (+, -, *, or /): $Enter Second Number: 5.15

248.12 $ 5.15 = 0

Catching Various Exceptions

In the examples above, when we anticipated some type of problem, we instructed the compiler touse our default Catch section. We left it up to the compiler to find out when there was a problemand we provided a Catch section to deal with it. A method with numerous or complex operationsand requests can also produce different types of errors. With such a type of program, you shouldbe able to face different problems and deal with them individually, each by its own kind. To dothis, you can create different Catch sections, each made for a particular error. The formula usedwould be:

Try ' Code to TryCatch One Type of Exception ' One ExceptionCatch Another Type Of Exception ' Another ExceptionEnd Try

The compiler would proceed in a top-down:

1. Following the normal flow of the program, the compiler enters the Try block

2. If no exception occurs in the Try block, the rest of the Try block is executedIf an exception occurs in the Try block, the compiler registers the type of error that occurred.If there is a throw line, the compiler registers it also:

a. The compiler gets out of the Try section

b. The compiler examines the first Catch. If the first Catch matches the thrown error, thatcatch executes and the exception handling routine may seize. If the first Catch doesn’tmatch the thrown error, the compiler proceeds with the next Catch

c. The compiler checks the next match, if any and proceeds as in the first match. Thiscontinues until the compiler finds a Catch that matches the thrown error

d. If one of the catches matches the thrown error, its body executes. If no Catch matchesthe thrown error, the compiler calls the Exception class and uses the default message

Multiple catches are written if or when a try block is expected to throw different types of errors.

This program works fine as long as the user types a valid sequence of values made of a number, avalid arithmetic operator, and a number. Anything else, such an invalid number, an unexpectedoperator, or a wrong sequence (such as a number then another number instead of an operator),would cause an error to be thrown. Obviously various bad things could happen when this programis running. To handle the exceptions that this program could produce, you can start with the mostlikely problem that would occur. Trusting that a user is able to provide the two numbers that arerequested, it is possible that a user would type an invalid operator. For example, for this programwe will perform only the addition (+), the subtraction(-), the multiplication(*), and the division(/).Therefore, we will first validate the operator. This can be done as follows:

Public Class Exercise Public Function Main() As Integer Dim Number1 As Double, Number2 As Double Dim Operator As String Dim Result As Double

Try Console.Write("Enter First Number: ") Number1 = CDbl(Console.ReadLine()) Console.Write("Enter Operation (+, -, *, or /): ") Operator = CStr(Console.ReadLine()) Console.Write("Enter Second Number: ") Number2 = CDbl(Console.ReadLine())

If Operator <> "+" And Operator <> "-" And _ Operator <> "*" And Operator <> "/" Then Throw New Exception(Operator) End If

If Operator = "+" Then Result = Number1 + Number2 ElseIf Operator = "-" Then Result = Number1 - Number2 ElseIf Operator = "*" Then Result = Number1 * Number2 ElseIf Operator = "/" Then Result = Number1 / Number2

Page 458: Microsoft Visual Basic 2010 Tutorial

Else Result = 0 End If

Console.WriteLine(vbCrLf & "{0} {1} {2} = {3}", _ Number1, Operator, Number2, Result) Catch ex As Exception Console.WriteLine(vbCrLf & "Invalid Operator: {0}", Operator) Console.WriteLine("Your operation could not be performed") End Try Return 0 End SubEnd Class

When this program runs, if the user provides a invalid operator, we register the operator by callingthe Exception(string message) constructor and pass it the wrong operator. If this error occurs,the compiler gets out of the Try block, it starts looking for and finds a Catch clause that receivesan Exception exception. Therefore, this Catch is executed. Here is an example of running theprogram:

Enter First Number: 1255.85Enter Operation (+, -, *, or /): +Enter Second Number: 704.62

1255.85 + 704.62 = 1960.47

Here is another example of running the same program:

Enter First Number: 1255.85Enter Operation (+, -, *, or /): @Enter Second Number: 704.62

Invalid Operator: @Your operation could not be performed

Here is another example of running the progvram:

Enter First Number: 124.05Enter Operation (+, -, *, or /): /Enter Second Number: 0

124.05 / 0 = Infinity

Imagine that the user wants to perform a division. You need to tell the compiler what to do if theuser enters the denominator as 0 (or 0.00). If this happens, the best option, and probably theonly one you should consider is to display a message and get out. Fortunately, the .NETFramework provides the DivideByZeroException class to deal with an exception caused bydivision by zero. As done with the message passed to the Exception class, you can compose yourown message and pass it to the DivideByZeroException(string message) constructor.

Exception is the parent of all exception classes. Therefore, if you write various catch blocks, theone that takes the Exception as argument must be the last.

Here is an example that catches two types of exceptions:

Public Class Exercise Public Function Main() As Integer Dim Number1 As Double, Number2 As Double Dim Operator As String Dim Result As Double

Try Console.Write("Enter First Number: ") Number1 = CDbl(Console.ReadLine()) Console.Write("Enter Operation (+, -, *, or /): ") Operator = CStr(Console.ReadLine()) Console.Write("Enter Second Number: ") Number2 = CDbl(Console.ReadLine())

If Operator <> "+" And Operator <> "-" And _ Operator <> "*" And Operator <> "/" Then Throw New Exception(Operator) End If

If Operator = "/" And Number2 = 0 Then Throw New DivideByZeroException("Division by zero is not allowed") End If

If Operator = "+" Then Result = Number1 + Number2 ElseIf Operator = "-" Then Result = Number1 - Number2 ElseIf Operator = "*" Then Result = Number1 * Number2 ElseIf Operator = "/" Then Result = Number1 / Number2 Else Result = 0 End If

Console.WriteLine(vbCrLf & "{0} {1} {2} = {3}", _ Number1, Operator, Number2, Result)

Console.WriteLine() Catch ex As DivideByZeroException

Page 459: Microsoft Visual Basic 2010 Tutorial

Console.WriteLine(ex.Message) Catch ex As Exception Console.WriteLine("Invalid Operator: {0}", Operator) Console.WriteLine("Your operation could not be performed") End Try Return 0 End SubEnd Class

When running this program, if the user types a wrong operator, the compiler gets out the Tryblock and looks for a Catch that takes an Exception as argument. It finds the second andexecutes it.

If the user enters two valid numbers, then the compiler finds out if the operator entered was aforward slash “/” used to perform a division. If the user wants to perform a division, the compilerfinds out if the second operand, the denominator, is 0. If it is, we create aDivideByZeroException instance and pass our own message to it. Based on this exception, thecompiler gets out of the Try block and starts looking for a Catch block that considers aDivideByZeroException exception. It finds it in the first catch. Therefore, the compiler executesit.

Here is an example of executing the program:

Enter First Number: 1288.24Enter Operation (+, -, *, or /): *Enter Second Number: 4.06

1288.24 * 4.06 = 5230.2544

Here is another example of executing the same program:

Enter First Number: 125.85Enter Operation (+, -, *, or /): /Enter Second Number: 5.05

125.85 / 5.05 = 24.9207920792079

Here is another example of executing the same program:

Enter First Number: 808.82Enter Operation (+, -, *, or /): /Enter Second Number: 0Division by zero is not allowed

Exceptions Nesting

The calculator simulator we have studied so far performs a division as one of its assignments. Welearned that, in order to perform any operation, the compiler must first make sure that the userhas entered a valid operator. Provided the operator is one of those we are expecting, we also mustmake sure that the user typed valid numbers. Even if these two criteria are met, it was possiblethat the user enter 0 for the denominator. The block that is used to check for a non-zerodenominator depends on the exception that validates the operators.

You can create an exception inside of another. This is referred to as nesting an exception. This isdone by applying the same techniques we used to nest conditional statements. This means thatyou can write an exception that depends on, and is subject to, another exception. To nest anexception, write a Try block in the body of the parent exception. The nested Try block must befollowed by its own Catch(es) clause. To effectively handle the exception, make sure you includean appropriate Throw in the Try block. Here is an example:

Public Class Exercise Public Function Main() As Integer Dim Number1 As Double, Number2 As Double Dim Operator As String Dim Result As Double

Try Console.Write("Enter First Number: ") Number1 = CDbl(Console.ReadLine()) Console.Write("Enter Operation (+, -, *, or /): ") Operator = CStr(Console.ReadLine()) Console.Write("Enter Second Number: ") Number2 = CDbl(Console.ReadLine()) Console.WriteLine()

If Operator <> "+" And Operator <> "-" And _ Operator <> "*" And Operator <> "/" Then Throw New Exception(Operator) End If

If Operator = "+" Then Result = Number1 + Number2 Console.WriteLine(vbCrLf & "{0} {1} {2} = {3}", _ Number1, Operator, Number2, Result)

ElseIf Operator = "-" Then Result = Number1 - Number2 Console.WriteLine(vbCrLf & "{0} {1} {2} = {3}", _ Number1, Operator, Number2, Result)

ElseIf Operator = "*" Then

Page 460: Microsoft Visual Basic 2010 Tutorial

Result = Number1 * Number2 Console.WriteLine(vbCrLf & "{0} {1} {2} = {3}", _ Number1, Operator, Number2, Result)

ElseIf Operator = "/" Then Try If Number2 = 0 Then Throw New DivideByZeroException( _ "Division by zero is not allowed") End If

Result = Number1 / Number2 Console.WriteLine(vbCrLf & "{0} {1} {2} = {3}", _ Number1, Operator, Number2, Result)

Catch ex As DivideByZeroException Console.WriteLine(ex.Message) End Try

Else Result = 0 End If

Catch ex As Exception Console.WriteLine("Invalid Operator: {0}", Operator) Console.WriteLine("Your operation could not be performed") End Try Return 0 End SubEnd Class

Here is an example of running the program:

Enter First Number: 125.55Enter Operation (+, -, *, or /): /Enter Second Number: 42.05

125.55 / 42.05 = 2.98573127229489

Here is another example of running the program:

Enter First Number: 125.55Enter Operation (+, -, *, or /): /Enter Second Number: 0

Division by zero is not allowed

Home Copyright © 2009-2010 FunctionX, Inc.

Page 461: Microsoft Visual Basic 2010 Tutorial

Introduction to File Processing

Overview of File Processing and Definitions

Introduction

In Lesson 2, we saw that a piece of information used in an application is primarily representedas a group of bits. So far, if we requested information from the user, when the applicationexited, we lost all information that the user had entered. This is because such information wasonly temporarily stored in the random access memory (RAM).

In some cases, you will want to "keep" information that the user has entered so you can make thesame values available the next time the user opens the application. In some other cases, whetheryou request information from the user or inherently provide it to the user, you may want differentpeople working from different computers to use or share the same data. In these and otherscenarios, you must store the information somewhere and retrieve it when necessary. This is thebasis of file processing.

Files

A file is a series of bytes of data that are arranged in a particular way to produce a usabledocument. For easy storage, location, and management, the bytes are stored on a medium suchas a hard disc, a floppy disc, a compact disc, or any valid and support type of storage. When thesebytes belong to a single but common entity and hold values that are stored on a medium, thegroup is referred to as a file. For even greater management, files can be stored in a parent objectcalled a directory or a folder. Since a file is a unit of storage and it stores information, it has asize, which is the number of bits it uses to store its values. To manage it, a file has a location alsocalled a path that specifies where and/or how the file can be retrieved. Also, for bettermanagement, a file has attributes that indicate what can be done on the file or that providespecific information that the programmer or the operating system can use when dealing with thefile.

Streams

File processing consists of creating, storing, and/or retrieving the contents of a file from arecognizable medium. For example, it is used to save word-processed files to a hard drive, tostore a presentation on floppy disk, or to open a file from a CD-ROM. A stream is the technique ormeans of performing file processing. In order to manage files stored in a computer, each file mustbe able to provide basic pieces of information about itself. This basic information is specified whenthe file is created but can change during the life time of a file.

To create a file, a user must first decide where it would be located: this is a requirement. A file canbe located on the root drive. Alternatively, a file can be positioned inside of an existing folder.Based on security settings, a user may not be able to create a file just anywhere in the (filesystem of the) computer. Once the user has decided where the file would reside, there are variousmeans of creating files that the users are trained to use. When creating a file, the user must giveit a name following the rules of the operating system combined with those of the file system. Themost fundamental piece of information a file must have is a name.

Once the user has created a file, whether the file is empty or not, the operating system assignsbasic pieces of information to it. Once a file is created, it can be opened, updated, modified,renamed, etc.

Streaming Prerequisites

Introduction

To support file processing, the .NET Framework provides the System.IO namespace that containsmany different classes to handle almost any type of file operation you may need to perform.Therefore, to perform file processing, include the System.IO namespace in your calls.

The parent class of file processing is Stream. With Stream, you can store data to a stream or youcan retrieve data from a stream. Stream is an abstract class, which means that you cannot use itto declare a variable in your application. As an abstract class, Stream is used as the parent of theclasses that actually implement the necessary operations. You will usually use a combination ofclasses to perform a typical operation. For example, some classes are used to create a streamobject while some others are used to write data to the created stream.

Page 462: Microsoft Visual Basic 2010 Tutorial

Practical Learning: Introducing Streaming

1. Start Notepad and type the following in the empty file: ' This class is used to create and manage an ice cream' and to process an orderPublic NotInheritable Class IceCream ' This is the base price of an ice cream ' Optional values may be added to it Public Const BasePrice As Double = 1.55

' These arrays are used to build the components of various ice creams ' In C#, we can allocate an array's memory in the body of the class Private Flavors As Collection Private Containers As Collection Private Ingredients As Collection

' Additional factor used to process an ice cream order Private Scoops As Integer Private TotalPrice As Double

' Variables that will hold the user's choice ' These are declared "globally" so they can be shared among methods Dim ChoiceFlavor As Integer Dim ChoiceContainer As Integer Dim ChoiceIngredient As Integer

' This default constructor is the best place for us to initialize the array Public Sub New() Flavors = New Collection Flavors.Add("Vanilla") Flavors.Add("Cream of Cocoa") Flavors.Add("Chocolate Chip") Flavors.Add("Organic Strawberry") Flavors.Add("Butter Pecan") Flavors.Add("Cherry Coke") Flavors.Add("Chocolate Brownies") Flavors.Add("Caramel Au Lait") Flavors.Add("Chunky Butter") Flavors.Add("Chocolate Cookie")

Ingredients = New Collection Ingredients.Add("No Ingredient") Ingredients.Add("Peanuts") Ingredients.Add("M & M") Ingredients.Add("Cookies")

Containers = New Collection Containers.Add("Cone") Containers.Add("Cup") Containers.Add("Bowl") End Sub

' This method requests a flavor from the user and returns the choice Public Sub ChooseFlavor() ' Make sure the user selects a valid number that represents a flavor... Do ' In case the user types a symbol that is not a number Try Console.WriteLine("What type of flavor do you want?") For i As Integer = 1 To Flavors.Count Step 1 Console.WriteLine("{0} - {1}", i, Flavors(i)) Next Console.Write("Your Choice? ") ChoiceFlavor = CInt(Console.ReadLine()) Catch ex As InvalidCastException ' display an appropriate message Console.WriteLine("You must enter a valid number " & _ "and no other character!") End Try

' If the user typed an invalid number out of the allowed range ' let him or her know and provide another chance If ChoiceFlavor < 1 Or ChoiceFlavor > Flavors.Count Then Console.WriteLine("Invalid Choice - Try Again!" & vbCrLf) End If Loop While ChoiceFlavor < 1 Or ChoiceFlavor > Flavors.Count End Sub

' This method allows the user to select a container Public Sub ChooseContainer() ' Make sure the user selects a valid number that represents a container Do ' If the user types a symbol that is not a number Try Console.WriteLine("What type of container do you want?") For i As Integer = 1 To Containers.Count Step 1 Console.WriteLine("{0} - {1}", i, Containers(i)) Next Console.Write("Your Choice? ") ChoiceContainer = CInt(Console.ReadLine()) Catch ex As InvalidCastException Console.WriteLine("You must enter a valid number " & _ "and no other character!") End Try

Page 463: Microsoft Visual Basic 2010 Tutorial

' If the user typed an invalid number out of the allowed range ' let him or her know and provide another chance If ChoiceContainer < 1 Or ChoiceContainer > Containers.Count Then Console.WriteLine("Invalid Choice - Try Again!") End If Loop While ChoiceContainer < 1 Or ChoiceContainer > Containers.Count End Sub

Public Sub ChooseIngredient() Do Try Console.WriteLine("Do you want an ingredient or not") For i As Integer = 1 To Ingredients.Count Step 1 Console.WriteLine("{0} - {1}", i, Ingredients(i)) Next Console.Write("Your Choice? ") ChoiceIngredient = CInt(Console.ReadLine()) Catch ex As InvalidCastException Console.WriteLine("You must enter a valid number " & _ "and no other character!") End Try

If ChoiceIngredient < 1 Or _ ChoiceIngredient > Ingredients.Count Then Console.WriteLine("Invalid Choice - Try Again!") End If Loop While ChoiceIngredient < 1 Or _ ChoiceIngredient > Ingredients.Count End Sub

Public Sub SpecifyNumberOfScoops() Do Try Console.Write("How many scoops(1, 2, or 3)? ") Scoops = CInt(Console.ReadLine()) Catch ex As InvalidCastException Console.WriteLine("You must enter a valid number " & _ "and no other character!") End Try

If Scoops < 1 Or Scoops > 3 Then Console.WriteLine("Invalid Choice - Try Again!") End If Loop While Scoops < 1 Or Scoops > 3 End Sub

' This method is used to process a customer order ' It uses the values of the above methods Public Sub ProcessAnOrder() Dim PriceIngredient As Double Dim PriceScoop As Double

' Let the user know that this is a vending machine Console.WriteLine("Ice Cream Vending Machine")

' Let the user select the components of the ice cream ChooseFlavor() ChooseContainer() ChooseIngredient() SpecifyNumberOfScoops()

' If the user selects an ingredient instead of "No Ingredient", ' add $0.50 to the order If ChoiceIngredient = 2 Or _ ChoiceIngredient = 3 Or _ ChoiceIngredient = 4 Then PriceIngredient = 0.5 Else PriceIngredient = 0.0 End If

' Instead of multiplying a number scoops to a value, ' We will use an incremental value depending on the number of scoops If Scoops = 1 Then PriceScoop = 0.65 ElseIf Scoops = 2 Then PriceScoop = 1.05 Else PriceScoop = 1.55 End If

' Calculate the total price of the ice cream TotalPrice = BasePrice + PriceScoop + PriceIngredient

' Create the ice cream...

' And display a receipt to the user DisplayReceipt() End Sub

' This method is used to display a receipt to the user Public Sub DisplayReceipt() Console.WriteLine(vbCrLf & "Ice Cream Order") Console.WriteLine("Flavor: {0}", Flavors(ChoiceFlavor)) Console.WriteLine("Container: {0}", Containers(ChoiceContainer)) Console.WriteLine("Ingredient: {0}", Ingredients(ChoiceIngredient)) Console.WriteLine("Scoops: {0}", Scoops)

Page 464: Microsoft Visual Basic 2010 Tutorial

Console.WriteLine("Total Price: {0:C}" & vbCrLf, TotalPrice) End SubEnd Class

2. Save the file in a new folder named IceCream4

3. Save the file itself as IceCream.vb in the IceCream4 folder

4. Start a new instance of Notepad and type the following in it: Imports System

Public Class Exercise Public Shared Sub main() Dim IC As IceCream = New IceCream

IC.ProcessAnOrder() End SubEnd Class

5. Save the file as Exercise.vb in the IceCream4 folder

6. Open the Command Prompt and change to the directory that contains the above Exercise.vbfile

7. To compile it, type vbc /out:"Ice Cream Vending Machine".exe IceCream.vb Exercise.vband press Enter

8. To execute it, type "Ice Cream Vending Machine" and press Enter. Here is an example: Ice Cream Vending MachineWhat type of flavor do you want?1 - Vanilla2 - Cream of Cocoa3 - Chocolate Chip4 - Organic Strawberry5 - Butter Pecan6 - Cherry Coke7 - Chocolate Brownies8 - Caramel Au Lait9 - Chunky Butter10 - Chocolate CookieYour Choice? 8What type of container do you want?1 - Cone2 - Cup3 - BowlYour Choice? 0Invalid Choice - Try Again!What type of container do you want?1 - Cone2 - Cup3 - BowlYour Choice? -1Invalid Choice - Try Again!What type of container do you want?1 - Cone2 - Cup3 - BowlYour Choice? 1Do you want an ingredient or not1 - No Ingredient2 - Peanuts3 - M & M4 - CookiesYour Choice? 5Invalid Choice - Try Again!Do you want an ingredient or not1 - No Ingredient2 - Peanuts3 - M & M4 - CookiesYour Choice? 4How many scoops(1, 2, or 3)? 2

Ice Cream OrderFlavor: Caramel Au LaitContainer: ConeIngredient: CookiesScoops: 2Total Price: $3.10

9. Return to the IceCream.vb file

The Name of a File

Before performing file processing, one of your early decisions will consist of specifying the type ofoperation you want to conduct. For example, you may want to create a brand new file. You maywant to open an existing file. Or you may want to perform a routine operation on a file. In all ormost cases, whether you are creating a new file or manipulating an existing one, you must specifythe name of the file. You can do this by declaring a string variable but most classes uses to createa stream as we will learn later can take a string that represents the file.

If you are creating a new file, there are certainly some rules you must observe. The name of a filefollows the directives of the operating system. On MS DOS and Windows 3.X (that is, prior to

Page 465: Microsoft Visual Basic 2010 Tutorial

Microsoft Windows 9X), the file had to use the 8.3 format. The actual name had to have amaximum of 8 characters with restrictions on the characters that could be used. The user also hadto specify three characters after a period. The three characters, known as the file extension, wereused by the operating system to classify the file. That was all necessary for those 8-bit and 16-bitoperating systems. Various rules have changed. For example, the names of folders and files onMicrosoft Windows >= 95 can have up to 255 characters. The extension of the file is mostly left tothe judgment of the programmer but the files are still using extensions. Applications can also beconfigured to save different types of files that is, files with different extensions.

At the time of this writing, the rules for file names for Microsoft Windows were on theMSDN web site at Windows Development\Windows Base Services\Files and I/O\SDKDocumentation\Storage\Storage Overview\File Management\Creating, Deleting, andMaintaining Files\Naming a File (because it is a web site and not a book, its pages canchange anytime).

Based on this, if you declare a string variable to hold the name of the file, you can simply initializethe variable with the necessary name and its extension. Here is an example:

Imports System

Public Class Exercise Public Shared Sub main() Dim NameOfFile As String = "Employees.spr"

End SubEnd Class

Practical Learning: Specifying the Name of a File

1. Access the IceCream.vb file and add a new public method named SaveOrder of type sub: ' This class is used to create and manage an ice cream' and to process an orderPublic NotInheritable Class IceCream

. . . No Change

' This method is used to display a receipt to the user Public Sub DisplayReceipt() Console.WriteLine(vbCrLf & "Ice Cream Order") Console.WriteLine("Flavor: {0}", Flavors(ChoiceFlavor)) Console.WriteLine("Container: {0}", Containers(ChoiceContainer)) Console.WriteLine("Ingredient: {0}", Ingredients(ChoiceIngredient)) Console.WriteLine("Scoops: {0}", Scoops) Console.WriteLine("Total Price: {0:C}" & vbCrLf, TotalPrice) End Sub

Public Sub Save() Dim NameOfFile As String

Console.Write("Please enter your initials or the name we " & _ "will use to remember your order: ") NameOfFile = Console.ReadLine() End SubEnd Class

2. Save the file

3. Access the Exercise.vb file and change it as follows: Imports System

Public Class Exercise Public Shared Sub main() Dim IC As IceCream = New IceCream Dim Answer As String

IC.ProcessAnOrder()

Console.Write("Do you want us to remember this order the next " & _ "time you come to get your ice cream (y/n)? ") Answer = Console.ReadLine()

If Answer = "y" Or Answer = "Y" Then IC.Save() End If End SubEnd Class

4. Save the file

5. Compile and execute it

1.

Page 466: Microsoft Visual Basic 2010 Tutorial

The Path to a File

If you declare a string as above, the file will be created in the folder of the application. Otherwise,you can create your new file anywhere on a medium such as the hard drive. To do that, you mustprovide a complete path where the file will reside. A path is a string that specifies the drive (suchas A:, C:, or D:). The sections of a complete path as string are separated by a backslash. Forexample, a path can the made of a folder followed by the name of the file. An example would be

C:\Palermo.tde

A path can also consist of a drive followed by the name of the folder in which the file will becreated. Here is an example:

C:\Program Files\Palermo.tde

A path can also indicate that the file will be created in a folder that itself is inside of anotherfolder. In this case, remember that the names of folders must be separated by backslashes. In thesame way, you can declare a string variable to represent the name of an existing file that you planto use in your program. You can also represent its path.

When providing a path to the file, if the drive you specify doesn't exist or cannot be read, thecompiler would consider that the file doesn't exist. If you provide folders that don't exist in thedrive, the compiler would consider that the file doesn't exist. This also means that the compilerwill not create the folder(s) (the .NET Framework provides all means to create a folder but youmust ask the compiler to create it; simply specifying a folder that doesn't exist will notautomatically create it, even if you are creating a new file). Therefore, it is your responsibility tomake sure that either the file or the path to the file is valid. As we will see in the next section, thecompiler can check the existence of a file or path.

File Existence

While Stream is used as the parent of all file processing classes, the .NET Framework provides theFile class equipped with methods to create, save, open, copy, move, delete, or provide detailedinformation about, files. Based on its functionality, the File class is typically used to assist theother classes with their processing operations. To effectively provide this support, all File'smethods are static which means that you will usually not need to declare a File variable to accessthem.

One of the valuable operations that the File class can perform is to check the existence of the fileyou want to use. For example, if you are creating a new file, you may want to make sure itdoesn't exist already because if you try to create a file that exists already, the compiler may firstdelete the old file before creating the new one. This could lead to unpredictable result, especiallybecause such a file is not sent to the Recycle Bin. On the other hand, if you are trying to open afile, you should first make sure the file exists, otherwise the compiler will not be able to open a fileit cannot find.

To check the existence of a file, the File class provides the Exists method. Its syntax is:

Public Shared Function Exists(ByVal path As String) As Boolean

If you provide only the name of the file, the compiler would check it in the folder of theapplication. If you provide the path to the file, the compiler would check its drive, its folder(s) andthe file itself. In both cases, if the file exists, the method returns true. If the compiler cannot findthe file, the method returns false. It's important to know that if you provided a complete path tothe file, any slight mistake would produce a false result.

Practical Learning: Checking the Existence of a File

1. Access the IceCream.vb file and change it as follows: Imports SystemImports System.IO

' This class is used to create and manage an ice cream' and to process an orderPublic NotInheritable Class IceCream

. . . No Change

Public Sub Save() Dim NameOfFile As String

Console.Write("Please enter your initials or the name " & _ "we will use to remember your order: ") NameOfFile = Console.ReadLine()

If File.Exists(NameOfFile) Then

Dim Answer As String

Console.WriteLine("The file you entered exists already.") Console.Write("Do you want to replace it(y/n)?") Answer = Console.ReadLine()

Page 467: Microsoft Visual Basic 2010 Tutorial

If Answer = "y" Or Answer = "Y" Then Console.WriteLine("The former order with the " & _ "same name will be replaced") ElseIf Answer = "n" Or Answer = "N" Then Console.WriteLine("Please enter a name we will " & _ "use to remember this order: ") NameOfFile = Console.ReadLine() Else Console.WriteLine("Invalid Answer - We will close") Exit Sub End If Else Console.WriteLine("The name you entered is not " & _ "registered in our previous orders") End If End Sub

Public Sub Open() Dim NameOfFile As String

Console.Write("Please enter the name you previously " & _ "gave to remember your order: ") NameOfFile = Console.ReadLine()

If File.Exists(NameOfFile) Then Console.WriteLine("The file would have been opened") Else Console.WriteLine("The name you entered is not " & _ "registered in our previous orders") End If End SubEnd Class

2. Save the file

3. Access the Exercise.vb file and change it as follows: Imports System

Public Class Exercise Public Shared Sub main() Dim IC As IceCream = New IceCream Dim Answer As String = "n"

Console.Write("Have you ordered here before(y/n)? ") Answer = Console.ReadLine()

If Answer = "y" Or Answer = "Y" Then IC.Open() Else

IC.ProcessAnOrder()

Console.Write("Do you want us to remember this order the " & _ "next time you come to get your ice cream (y/n)? ") Answer = Console.ReadLine()

If Answer = "y" Or Answer = "Y" Then IC.Save() End If End If

End SubEnd Class

4. Save the file

5. Compile and execute it

Access to a File

In order to perform an operation on a file, you must specify to the operating system how toproceed. One of the options you have is to indicate the type of access that will be granted on thefile. This access is specified using the FileAccess enumerator. The members of the FileAccessenumerator are:

FileAccess.Write: New data can be written to the file

FileAccess.Read: Existing data can be read from the file

FileAccess.ReadWrite: Existing data can be read from the file and new data be written to thefile

File Sharing

In standalone workstations, one person is usually able to access and open a file then perform thenecessary operations on it. In networked computers, you may create a file that different peoplecan access at the same time or you may make one file access another file to retrieve information.For example, suppose you create an application for a fast food restaurant that has two or moreconnected workstations and all workstations save their customers orders to a common file. In thiscase, you must make sure that any of the computers can access the file to save an order. An

Page 468: Microsoft Visual Basic 2010 Tutorial

employee from one of these workstations must also be able to open the file to retrieve a customerorder for any necessary reason. You can also create a situation where one file holds an inventoryof the items of a store and another file holds the customers orders. Obviously one file woulddepend on another. Based on this, when an operation must be performed on a file, you may haveto specify how a file can be shared. This is done through the FileShare enumerator.

The values of the FileShare enumerator are:

FileShare.Inheritable: Allows other file handles to inherit from this file

FileShare.None: The file cannot be shared

FileShare.Read: The file can be opened and read from

FileShare.Write: The file can be opened and written to

FileShare.ReadWrite: The file can be opened to write to it or read from it

The Mode of a File

Besides the access to the file, another option you will most likely specify to the operating systemis referred to as the mode of a file. It is specified through the FileMode enumerator. Themembers of the FileMode Enumerator are:

FileMode.Append: If the file already exists, the new data will be added to its end. If the filedoesn't exist, it will be created and the new data will be added to it

FileMode.Create: If the file already exists, it will be deleted and a new file with the samename will be created. If the file doesn't exist, then it will be created

FileMode.CreateNew: If the new already exists, the compiler will throw an error. If the filedoesn't exist, it will be created

FileMode.Open: If the file exists, it will be opened. If the file doesn't exist, an error would bethrown

FileMode.OpenOrCreate: If the file already exists, it will be opened. If the file doesn't exist,it will be created

FileMode.Truncate: If the file already exists, its contents will be deleted completely but thefile will be kept, allowing you to write new data to it. If the file doesn't exist, an error wouldbe thrown

Home Copyright © 2009-2010 FunctionX, Inc. Next

Page 469: Microsoft Visual Basic 2010 Tutorial

File Streams

Fundamental File Streaming

Introduction to File Streaming

File streaming consists of performing one of the routine operations on a file, such as creating it oropening it. This basic operation can be performed using a class called FileStream. You can use aFileStream object to get a stream ready for processing.

As one of the most complete classes of file processing of the .NET Framework, FileStream isequipped with all necessary properties and methods. To use it, you must first declare a variable ofit. The class is equipped with nine constructors.

One of the constructors (the second) of the FileStream class has the following syntax:

Public Sub New(ByVal path As String, ByVal mode As FileMode)

This constructor takes as its first argument the name or the file or its path. The second argumentspecifies the type of operation to perform on the file. Here is an example:

Imports SystemImports System.IO

Public Class Exercise Public Shared Sub main() Dim NameOfFile As String = "Persons.spr"

Dim fstPersons As FileStream = New FileStream(NameOfFile, FileMode.Create) End SubEnd Class

Stream Writing

A streaming operation is typically used to create a stream. Once the stream is ready, you can writedata to it. The writing operation is perform through various classes. One of these classes isBinaryWriter.

The BinaryWriter class can be used to write values of primitive data types (char, int, float,double, etc). To use a BinaryWriter value, you can first declare its variable. To do this, youwould use one of the class' three constructors. One of its constructors (the second) has thefollowing syntax:

Public Sub New(ByVal output As Stream)

This constructor takes as argument a Stream value, which could be a FileStream variable. Here isan example:

Imports SystemImports System.IO

Public Class Exercise Public Shared Sub main() Dim NameOfFile As String = "Persons.spr"

Dim fstPersons As FileStream = New FileStream(NameOfFile, FileMode.Create) Dim wrtPersons As BinaryWriter = New BinaryWriter(fstPersons) End SubEnd Class

Most classes that are used to add values to a stream are equipped with a method called Write.This is also the case for the BinaryWriter class. This method takes as argument the value thatmust be written to the stream. The method is overloaded so that there is a version for eachprimitive data type. Here is an example that adds strings to a newly created file:

Imports SystemImports System.IO

Public Class Exercise Public Shared Sub main() Dim NameOfFile As String = "Persons.spr"

Dim fstPersons As FileStream = New FileStream(NameOfFile, FileMode.Create) Dim wrtPersons As BinaryWriter = New BinaryWriter(fstPersons)

wrtPersons.Write("James Bloch") wrtPersons.Write("Catherina Wallace") wrtPersons.Write("Bruce Lamont") wrtPersons.Write("Douglas Truth") End SubEnd Class

Page 470: Microsoft Visual Basic 2010 Tutorial

Stream Closing

When you use a stream, it requests resources from the operating system and uses them while thestream is available. When you are not using the stream anymore, you should free the resourcesand make them available again to the operating system so that other services can use them. Thisis done by closing the stream.

To close a stream, you can can call the Close() method of the class(es) you were using. Here areexamples:

Imports SystemImports System.IO

Public Class Exercise Public Shared Sub main() Dim NameOfFile As String = "Persons.spr"

Dim fstPersons As FileStream = New FileStream(NameOfFile, FileMode.Create) Dim wrtPersons As BinaryWriter = New BinaryWriter(fstPersons)

wrtPersons.Write("James Bloch") wrtPersons.Write("Catherina Wallace") wrtPersons.Write("Bruce Lamont") wrtPersons.Write("Douglas Truth")

wrtPersons.Close() fstPersons.Close() End SubEnd Class

Practical Learning: Writing to a Stream

1. To be able to complete a file, change the Save() method in the IceCream.vb file as follows: Public Sub Save() Dim NameOfFile As String

Console.WriteLine("Please enter your initials or the name " & _ "we will use to remember your order: ") NameOfFile = Console.ReadLine() NameOfFile = NameOfFile & ".icr"

' Find out if the user entered a name of a file that " & _ "is already in the machine If File.Exists(NameOfFile) Then Dim Answer As String

Dim stmIceCream As FileStream = _ New FileStream(NameOfFile, FileMode.Create) Dim bnwIceCream As BinaryWriter = New BinaryWriter(stmIceCream)

' If so, find out if the user wants to replace the old file Console.WriteLine("The file you entered exists already.") Console.Write("Do you want to replace it(y/n)?") Answer = Console.ReadLine()

' If the customer wants to replace it... If Answer = "y" Or Answer = "Y" Then

' ... do so Console.WriteLine("The former order with the " & _ "same name will be replaced")

Console.WriteLine(vbCrLf & "=-= Ice Cream Vending Machine =-=") Console.WriteLine(" Saving Order: {0}", NameOfFile) bnwIceCream.Write(Flavors(ChoiceFlavor)) bnwIceCream.Write(Containers(ChoiceContainer)) bnwIceCream.Write(Ingredients(ChoiceIngredient)) bnwIceCream.Write(Scoops) bnwIceCream.Write(TotalPrice)

' If the customer wants to save the new order with a different name ElseIf Answer = "n" Or Answer = "N" Then ' Ask the user to enter a name to remember the order Console.Write("Please enter a name we will " & _ "use to remember this order: ") NameOfFile = Console.ReadLine() NameOfFile = NameOfFile & ".icr"

stmIceCream = New FileStream(NameOfFile, FileMode.Create) bnwIceCream = New BinaryWriter(stmIceCream)

Console.WriteLine(vbCrLf & "=-= Ice Cream Vending Machine =-=") Console.WriteLine(" Saving Order: {0}", NameOfFile) bnwIceCream.Write(Flavors(ChoiceFlavor)) bnwIceCream.Write(Containers(ChoiceContainer)) bnwIceCream.Write(Ingredients(ChoiceIngredient)) bnwIceCream.Write(Scoops) bnwIceCream.Write(TotalPrice) Else Console.WriteLine("Invalid Answer - We will close") bnwIceCream.Close()

Page 471: Microsoft Visual Basic 2010 Tutorial

stmIceCream.Close() End If Else

Dim stmIceCream As FileStream = _ New FileStream(NameOfFile, FileMode.Create) Dim bnwIceCream As BinaryWriter = New BinaryWriter(stmIceCream)

Console.WriteLine(vbCrLf & "=-= Ice Cream Vending Machine =-=") Console.WriteLine(" Saving Order: {0}", NameOfFile) bnwIceCream.Write(Flavors(ChoiceFlavor)) bnwIceCream.Write(Containers(ChoiceContainer)) bnwIceCream.Write(Ingredients(ChoiceIngredient)) bnwIceCream.Write(Scoops) bnwIceCream.Write(TotalPrice)

bnwIceCream.Close() stmIceCream.Close() End If End Sub

2. Save the file and switch to the Command Prompt

3. To compile it, type vbc /out:"Ice Cream Vending Machine".exe IceCream.vb Exercise.vband press Enter

4. To execute it, type "Ice Cream Vending Machine" and press Enter. Here is an example: Have you ordered here before(y/n)? n

=-= Ice Cream Vending Machine =-= ------ New Customer Order ------What type of flavor do you want?1 - Vanilla2 - Cream of Cocoa3 - Chocolate Chip4 - Organic Strawberry5 - Butter Pecan6 - Cherry Coke7 - Chocolate Brownies8 - Caramel Au Lait9 - Chunky Butter10 - Chocolate CookieYour Choice? 7What type of container do you want?1 - Cone2 - Cup3 - BowlYour Choice? 1Do you want an ingredient or not1 - No Ingredient2 - Peanuts3 - M & M4 - CookiesYour Choice? 4How many scoops(1, 2, or 3)? 2

Ice Cream OrderFlavor: Chocolate BrowniesContainer: ConeIngredient: CookiesScoops: 2Total Price: $3.10

Do you want us to remember this order the next time you come to get your ice scream (y/n)? yPlease enter your initials or the name we will use to remember your order:Jane44

=-= Ice Cream Vending Machine =-= Saving Order: Jane44.icr

5. Return to the IceCream.vb file

Stream Reading

As opposed to writing to a stream, you may want to read existing data from it. Before doing this,you can first specify your intent to the streaming class using the FileMode enumerator. This canbe done using the FileStream class as follows:

Imports SystemImports System.IO

Public Class Exercise Public Shared Sub main() Dim NameOfFile As String = "Persons.spr"

Dim fstPersons As FileStream = New FileStream(NameOfFile, FileMode.Open)

End SubEnd Class

Once the stream is ready, you can get prepared to read data from it. To support this, you can usethe BinaryReader class. This class provides two constructors. One of the constructors (the first)

Page 472: Microsoft Visual Basic 2010 Tutorial

has the following syntax:

Public Sub New(ByVal input As Stream)

This constructor takes as argument a Stream value, which could be a FileStream object. Afterdeclaring a FileStream variable using this constructor, you can read data from it. To do this, youcan call an appropriate method. This class provides an appropriate method for each primitive datatype.

After using the stream, you should close it to reclaim the resources it was using. This is done bycalling the Close() method.

Here is an example of using the mentioned methods:

Imports SystemImports System.IO

Public Class Exercise Public Shared Sub main() Dim NameOfFile As String = "Persons.spr"

Dim fstPersons As FileStream = New FileStream(NameOfFile, FileMode.Open) Dim rdrPersons As BinaryReader = New BinaryReader(fstPersons) Dim strLine As String

strLine = rdrPersons.ReadString() Console.WriteLine(strLine) strLine = rdrPersons.ReadString() Console.WriteLine(strLine) strLine = rdrPersons.ReadString() Console.WriteLine(strLine) strLine = rdrPersons.ReadString() Console.WriteLine(strLine)

rdrPersons.Close() fstPersons.Close() End SubEnd Class

This would produce:

James BlochCatherina WallaceBruce LamontDouglas Truth

Practical Learning: Reading From a Stream

1. To be able to retrieve data from an existing file, change the OpenFile() method as follows: Source File: IceCream.vbImports SystemImports System.IO

' This class is used to create and manage an ice cream' and to process an orderPublic NotInheritable Class IceCream ' This is the base price of an ice cream ' Optional values may be added to it Public Const BasePrice As Double = 1.55

' These arrays are used to build the components of various ice creams ' In C#, we can allocate an array's memory in the body of the class Private Flavors As Collection Private Containers As Collection Private Ingredients As Collection

' Additional factor used to process an ice cream order Private Scoops As Integer Private TotalPrice As Double

' Variables that will hold the user's choice ' These are declared "globally" so they can be shared among methods Dim ChoiceFlavor As Integer Dim ChoiceContainer As Integer Dim ChoiceIngredient As Integer

' This default constructor is the best place ' for us to initialize the array Public Sub New() Flavors = New Collection Flavors.Add("Vanilla") Flavors.Add("Cream of Cocoa") Flavors.Add("Chocolate Chip") Flavors.Add("Organic Strawberry") Flavors.Add("Butter Pecan") Flavors.Add("Cherry Coke") Flavors.Add("Chocolate Brownies")

Page 473: Microsoft Visual Basic 2010 Tutorial

Flavors.Add("Caramel Au Lait") Flavors.Add("Chunky Butter") Flavors.Add("Chocolate Cookie")

Ingredients = New Collection Ingredients.Add("No Ingredient") Ingredients.Add("Peanuts") Ingredients.Add("M & M") Ingredients.Add("Cookies")

Containers = New Collection Containers.Add("Cone") Containers.Add("Cup") Containers.Add("Bowl") End Sub

' This method requests a flavor from the user and returns the choice Public Sub ChooseFlavor() ' Make sure the user selects a valid number that represents a flavor... Do ' In case the user types a symbol that is not a number Try Console.WriteLine("What type of flavor do you want?") For i As Integer = 1 To Flavors.Count Step 1 Console.WriteLine("{0} - {1}", i, Flavors(i)) Next Console.Write("Your Choice? ") ChoiceFlavor = CInt(Console.ReadLine()) Catch ex As InvalidCastException ' display an appropriate message Console.WriteLine("You must enter a valid " & _ "number and no other character!") End Try

' If the user typed an invalid number out of the allowed range ' let him or her know and provide another chance If ChoiceFlavor < 1 Or ChoiceFlavor > Flavors.Count Then Console.WriteLine("Invalid Choice - Try Again!" & vbCrLf) End If Loop While ChoiceFlavor < 1 Or ChoiceFlavor > Flavors.Count End Sub

' This method allows the user to select a container Public Sub ChooseContainer() ' Make sure the user selects a valid number that represents a container Do ' If the user types a symbol that is not a number Try Console.WriteLine("What type of container do you want?") For i As Integer = 1 To Containers.Count Step 1 Console.WriteLine("{0} - {1}", i, Containers(i)) Next Console.Write("Your Choice? ") ChoiceContainer = CInt(Console.ReadLine()) Catch ex As InvalidCastException Console.WriteLine("You must enter a valid " & _ "number and no other character!") End Try

' If the user typed an invalid number out of the allowed range ' let him or her know and provide another chance If ChoiceContainer < 1 Or ChoiceContainer > Containers.Count Then Console.WriteLine("Invalid Choice - Try Again!") End If Loop While ChoiceContainer < 1 Or ChoiceContainer > Containers.Count End Sub

Public Sub ChooseIngredient() Do Try Console.WriteLine("Do you want an ingredient or not") For i As Integer = 1 To

Page 474: Microsoft Visual Basic 2010 Tutorial

Ingredients.Count Step 1 Console.WriteLine("{0} - {1}", i, Ingredients(i)) Next Console.Write("Your Choice? ") ChoiceIngredient = CInt(Console.ReadLine()) Catch ex As InvalidCastException Console.WriteLine("You must enter a valid " & _ "number and no other character!") End Try

If ChoiceIngredient < 1 Or ChoiceIngredient > Ingredients.Count Then Console.WriteLine("Invalid Choice - Try Again!") End If Loop While ChoiceIngredient < 1 Or ChoiceIngredient > Ingredients.Count End Sub

Public Sub SpecifyNumberOfScoops() Do Try Console.Write("How many scoops(1, 2, or 3)? ") Scoops = CInt(Console.ReadLine()) Catch ex As InvalidCastException Console.WriteLine("You must enter a valid " & _ "number and no other character!") End Try

If Scoops < 1 Or Scoops > 3 Then Console.WriteLine("Invalid Choice - Try Again!") End If Loop While Scoops < 1 Or Scoops > 3 End Sub

' This method is used to process a customer order ' It uses the values of the above methods Public Sub ProcessAnOrder() Dim PriceIngredient As Double Dim PriceScoop As Double

' Let the user know that this is a vending machine Console.WriteLine("Ice Cream Vending Machine")

' Let the user select the components of the ice cream ChooseFlavor() ChooseContainer() ChooseIngredient() SpecifyNumberOfScoops()

' If the user selects an ingredient instead of "No Ingredient", ' add $0.50 to the order If ChoiceIngredient = 2 Or _ ChoiceIngredient = 3 Or _ ChoiceIngredient = 4 Then PriceIngredient = 0.5 Else PriceIngredient = 0.0 End If

' Instead of multiplying a number scoops to a value, ' We will use an incremental value depending on the number of scoops If Scoops = 1 Then PriceScoop = 0.65 ElseIf Scoops = 2 Then PriceScoop = 1.05 Else PriceScoop = 1.55 End If

' Calculate the total price of the ice cream TotalPrice = BasePrice + PriceScoop + PriceIngredient

' Create the ice cream...

' And display a receipt to the user DisplayReceipt() End Sub

' This method is used to display a receipt to the user Public Sub DisplayReceipt() Console.WriteLine(vbCrLf & "Ice Cream

Page 475: Microsoft Visual Basic 2010 Tutorial

Order") Console.WriteLine("Flavor: {0}", Flavors(ChoiceFlavor)) Console.WriteLine("Container: {0}", Containers(ChoiceContainer)) Console.WriteLine("Ingredient: {0}", Ingredients(ChoiceIngredient)) Console.WriteLine("Scoops: {0}", Scoops) Console.WriteLine("Total Price: {0:C}" & vbCrLf, TotalPrice) End Sub

Public Sub Save() Dim NameOfFile As String

Console.WriteLine("Please enter your initials or the name " & _ "we will use to remember your order: ") NameOfFile = Console.ReadLine() NameOfFile = NameOfFile & ".icr"

' Find out if the user entered a name of a ' file that is already in the machine If File.Exists(NameOfFile) Then Dim Answer As String

Dim stmIceCream As FileStream = _ New FileStream(NameOfFile, FileMode.Create) Dim bnwIceCream As BinaryWriter = New BinaryWriter(stmIceCream)

' If so, find out if the user wants to replace the old file Console.WriteLine("The file you entered exists already.") Console.Write("Do you want to replace it(y/n)?") Answer = Console.ReadLine()

' If the customer wants to replace it... If Answer = "y" Or Answer = "Y" Then

' ... do so Console.WriteLine("The former order with the " & _ "same name will be replaced")

Console.WriteLine(vbCrLf & "=-= Ice Cream Vending Machine =-=") Console.WriteLine(" Saving Order: {0}", NameOfFile) bnwIceCream.Write(Flavors(ChoiceFlavor)) bnwIceCream.Write(Containers(ChoiceContainer)) bnwIceCream.Write(Ingredients(ChoiceIngredient)) bnwIceCream.Write(Scoops) bnwIceCream.Write(TotalPrice)

' If the customer wants to save the ' new order with a different name ElseIf Answer = "n" Or Answer = "N" Then ' Ask the user to enter a name to remember the order Console.Write("Please enter a name we will " & _ "use to remember this order: ") NameOfFile = Console.ReadLine() NameOfFile = NameOfFile & ".icr"

stmIceCream = New FileStream(NameOfFile, FileMode.Create) bnwIceCream = New BinaryWriter(stmIceCream)

Console.WriteLine(vbCrLf & "=-= Ice Cream Vending Machine =-=") Console.WriteLine(" Saving Order: {0}", NameOfFile) bnwIceCream.Write(Flavors(ChoiceFlavor)) bnwIceCream.Write(Containers(ChoiceContainer)) bnwIceCream.Write(Ingredients(ChoiceIngredient)) bnwIceCream.Write(Scoops) bnwIceCream.Write(TotalPrice) Else

Page 476: Microsoft Visual Basic 2010 Tutorial

Console.WriteLine("Invalid Answer - We will close") bnwIceCream.Close() stmIceCream.Close() End If Else

Dim stmIceCream As FileStream = _ New FileStream(NameOfFile, FileMode.Create) Dim bnwIceCream As BinaryWriter = New BinaryWriter(stmIceCream)

Console.WriteLine(vbCrLf & "=-= Ice Cream Vending Machine =-=") Console.WriteLine(" Saving Order: {0}", NameOfFile) bnwIceCream.Write(Flavors(ChoiceFlavor)) bnwIceCream.Write(Containers(ChoiceContainer)) bnwIceCream.Write(Ingredients(ChoiceIngredient)) bnwIceCream.Write(Scoops) bnwIceCream.Write(TotalPrice)

bnwIceCream.Close() stmIceCream.Close() End If End Sub

Public Sub Open() Dim NameOfFile As String

Dim SelectedFlavor As String Dim SelectedContainer As String Dim SelectedIngredient As String

' Ask the user to enter a name of a previously saved order Console.Write("Please enter the name you previously " & _ "gave to remember your order: ") NameOfFile = Console.ReadLine() NameOfFile = NameOfFile & ".icr"

Dim stmIceCream As FileStream = New FileStream(NameOfFile, FileMode.Open) Dim bnrIceCream As BinaryReader = New BinaryReader(stmIceCream)

' Find out if this order was previously saved in the machine If File.Exists(NameOfFile) Then ' If so, open it SelectedFlavor = bnrIceCream.ReadString() SelectedContainer = bnrIceCream.ReadString() SelectedIngredient = bnrIceCream.ReadString() Scoops = bnrIceCream.ReadInt32() TotalPrice = bnrIceCream.ReadDouble()

' And display it to the user Console.WriteLine(vbCrLf & "=-= Ice Cream Vending Machine =-=") Console.WriteLine(" Previous Order: {0}", NameOfFile) Console.WriteLine("Flavor: {0}", SelectedFlavor) Console.WriteLine("Container: {0}", SelectedContainer) Console.WriteLine("Ingredient: {0}", SelectedIngredient) Console.WriteLine("Scoops: {0}", Scoops) Console.WriteLine("Total Price: {0:C}" & vbCrLf, TotalPrice)

bnrIceCream.Close() stmIceCream.Close() Else Console.WriteLine("The name you entered is not " & _ "registered in our previous orders") End If End SubEnd ClassSource File: Exercise.vbImports System

Public Class Exercise Public Shared Sub main() Dim IC As IceCream = New IceCream Dim Answer As String = "n"

Page 477: Microsoft Visual Basic 2010 Tutorial

Console.Write("Have you ordered here before(y/n)? ") Answer = Console.ReadLine()

If Answer = "y" Or Answer = "Y" Then IC.Open() Else

IC.ProcessAnOrder()

Console.Write("Do you want us to remember this order the next " & _ "time you come to get your ice cream (y/n)? ") Answer = Console.ReadLine()

If Answer = "y" Or Answer = "Y" Then IC.Save() End If End If

End SubEnd Class

2. Save the file and switch to the Command Prompt

3. To compile it, type vbc /out:"Ice Cream Vending Machine".exe IceCream.vb Exercise.vband press Enter

4. To execute it, type "Ice Cream Vending Machine" and press Enter. Here is an example: Have you ordered here before(y/n)? yPlease enter the name you previously gave to remember your order: Jane44

=-= Ice Cream Vending Machine =-= Previous Order: Jane44.icrFlavor: Chocolate BrowniesContainer: ConeIngredient: CookiesScoops: 2Total Price: $3.10

5. Return to the IceCream.vb file

Previous Copyright © 2009-2010 FunctionX, Inc. Next

Page 478: Microsoft Visual Basic 2010 Tutorial

Exception Handling in File Processing

Finally

So far, to handle exceptions, we were using the Try, Catch, and Throw keywords. Theseallowed us to perform normal assignments in a Try section and then handle an exception, if any,in a Catch block.

In the previous lesson, we mentioned that, when you create a stream, the operating system mustallocate resources and dedicate them to the file processing operations. Additional resources maybe provided for the object that is in charge of writing to, or reading from, the stream. We alsosaw that, when the streaming was over, we should free the resources and give them back to theoperating system. To do this, we called the Close() method of the variable that was usingresources.

More than any other assignment, file processing is in prime need of exception handling. As we willsee in the next section, during file processing, there are many things that can go wrong. For thisreason, the creation and/or management of streams should be performed in a Try block to getready to handle exceptions that would occur. Besides actually handling exceptions, SEH provides aspecial keyword used free resources. This keyword is Finally.

The Finally keyword is used to create a section of an exception. Like catch, a Finally block cannotexist by itself. It can be created following a Try section. The formula used would be:

Try

Finally

End Try

Based on this, the Finally section has a body of its own, delimited by its curly brackets. Likecatch, the Finally section is created after the Try section. Unlike Catch, Finally never hasparentheses and never takes arguments. Unlike Catch, the Finally section is always executed.Because the Finally clause always gets executed, you can include any type of code in it but it isusually appropriate to free the resources that were allocated earlier. Here is an example:

Imports SystemImports System.IO

Public Class Exercise Public Shared Sub main() Dim NameOfFile As String = "Members.clb"

Dim fstPersons As FileStream = New FileStream(NameOfFile, FileMode.Create) Dim wrtPersons As BinaryWriter = New BinaryWriter(fstPersons)

Try

wrtPersons.Write("James Bloch") wrtPersons.Write("Catherina Wallace") wrtPersons.Write("Bruce Lamont") wrtPersons.Write("Douglas Truth") Finally wrtPersons.Close() fstPersons.Close() End Try End SubEnd Class

In the same way, you can use a Finally section to free resources used when reading from astream:

Imports SystemImports System.IO

Public Class Exercise Public Shared Sub main() Dim NameOfFile As String = "Members.clb" Dim strLine As String

Dim fstMembers As FileStream = New FileStream(NameOfFile, FileMode.Open) Dim rdrMembers As BinaryReader = New BinaryReader(fstMembers)

Try strLine = rdrMembers.ReadString() Console.WriteLine(strLine) strLine = rdrMembers.ReadString() Console.WriteLine(strLine) strLine = rdrMembers.ReadString() Console.WriteLine(strLine) strLine = rdrMembers.ReadString() Console.WriteLine(strLine) Finally rdrMembers.Close()

Page 479: Microsoft Visual Basic 2010 Tutorial

fstMembers.Close() End Try End SubEnd Class

Of course, since the whole block of code starts with a Try section, it is used for exceptionhandling. This means that you can add the necessary and appropriate Catch section(s) but youdon't have to.

.NET Framework Exception Handling for File Processing

In the previous lesson as our introduction to file processing, we behaved as if everything wasalright. Unfortunately, file processing can be very strict in its assignments. Based on this, the .NETFramework provides various Exception-oriented classes to deal with almost any type of exceptionyou can think of.

One of the most important aspects of file processing is the name of the file that will be dealt with.In some cases you can provide this name to the application or document. In some other cases,you would let the user specify the name of the path. Regardless of how the name of the file wouldbe provided to the operating system, when this name is acted upon, the compiler be asked towork on the file. If the file doesn't exist, the operation cannot be carried. Furthermore, thecompiler would throw an error. There are many other exceptions that can thrown as a result ofsomething going bad during file processing:

FileNotFoundException: The exception thrown when a file has been found is of typeFileNotFoundException. Here is an example of handling it:

Imports SystemImports System.IO

Public Class Exercise Public Shared Sub main() Dim NameOfFile As String = "Associates.clb" Dim strLine As String

Try Dim fstMembers As FileStream = New FileStream(NameOfFile, FileMode.Open) Dim rdrMembers As BinaryReader = New BinaryReader(fstMembers) Try

strLine = rdrMembers.ReadString() Console.WriteLine(strLine) strLine = rdrMembers.ReadString() Console.WriteLine(strLine) strLine = rdrMembers.ReadString() Console.WriteLine(strLine) strLine = rdrMembers.ReadString() Console.WriteLine(strLine) Finally rdrMembers.Close() fstMembers.Close() End Try Catch ex As FileNotFoundException

Console.WriteLine("Error: " + ex.Message) Console.WriteLine("May be the file doesn't exist or you typed it wrong!") End Try End SubEnd Class

Here is an example of what this would produce:

Error: Could not find file "C:\Programs\MSVB .NET 2003\Project11\bin\Associates.clb".May be the file doesn't exist or you typed it wrong!

IOException: As mentioned already, during file processing, anything could go wrong. If you don'tknow what caused an error, you can throw the IOException exception.

Previous Copyright © 2008-2010 FunctionX, Inc. Next

Page 480: Microsoft Visual Basic 2010 Tutorial

Directories

Introduction

A directory is a section of a medium used to delimit a group of files. Because it is a "physical"area, it can handle operations not available on files. In fact, there are many fundamentaldifferences between both:

A file is used to contain data. A directory doesn't contain data

A directory can contain one or more files and not vice-versa

A directory can contain other directories

A file can be moved from one directory to another. This operation is not possible vice-versasince a file cannot contain a directory

The similarities of both types are:

A directory or a file can be created. One of the restrictions is that two files cannot have thesame name inside of the same directory. Two directories cannot have the same name inside ofthe same parent directory.

A directory or a file can be renamed. If a directory is renamed, the "path" of its files changes

A directory or a file can be deleted. If a directory is deleted, its files are deleted also

A directory or a file can be moved. If a directory moves, it "carries" all of its files to the newlocation

A directory or a file can be copied. One file can be copied from one directory to another. If adirectory if copied to a new location, all of its files are also copied to the new location

Directory Operations

Before using a directory, you must first have it. You can use an existing directory if the operatingsystem or someone else had already created one. You can also create a new directory. Directoriesare created and managed by various classes but the fundamental class is Directory. Additionaloperations are performed using the DirectoryInfo class.

Before using or creating a directory, you can first check if it exists. This is because, if a directoryalready exists in the location where you want to create it, you would be prevented from creatingone with the same name. In the same way, if you just decide to directly use a directory thatdoesn't exist, the operation you want to perform may fail because the directory would not befound.

Before using or creating a directory, to check first whether it exists or not, you can call theDirectory.Exists() Boolean method. Its syntax is:

Public Shared Function Exists(ByVal path As String) As Boolean

This method receives the (complete) path of the directory. If the path is verified, the methodreturns true. If the directory exists, the method returns false.

To create a directory, you can call the CreateDirectory() method of the Directory class.

Object Serialization

Introduction

File processing is usually thought of as the technique of storing or retrieving bits of data of valuesfrom primitive variables that, when grouped, belong to a file. This approach falls short when theinformation dealt with is managed at a class level. Fortunately, modern libraries allow fileprocessing on classes. In other words, a variable declared from a class can be saved to a streamand then the saved object can be retrieved later or on another computer. This the basis of objectserialization. This serialization works by manipulating a whole object as its own value rather thanits member variables.

The .NET Framework supports two types of object serialization: binary and XML.

Binary serialization works by processing an object rather than its member variables. This meansthat, to use it, you define an object and initialize it, or "fill" it, with the necessary values and anyinformation you judge necessary. This creates a "state" of the object. It is this state that you

Page 481: Microsoft Visual Basic 2010 Tutorial

prepare to serialize. When you save the object, it is converted into a stream.

XML Serialization

Thanks to its flexibility and platform independent way of dealing with values, XML is always aprima candidate for value serialization. Unlike strict object serialization, but like the techniques offile processing we reviewed earlier, XML considers the value members of an object, such as itsfields and properties, for serialization. This means that XML doesn't allow serializing an object asits own value, but you can implement an effective object serialization by the way you proceed.

Previous Copyright © 2009-2010 FunctionX, Inc. Home

Page 482: Microsoft Visual Basic 2010 Tutorial

Files

Detailed Operations on Files

File Creation

Besides checking the existence of the file, the File class can be used to create a new file. Tosupport this operation, the File class is equipped with the Create() method that is overloadedwith two versions as follows:

Overloads Public Shared Function Create( _ ByVal path As String _) As FileStreamOverloads Public Shared Function Create( _ ByVal path As String, _ ByVal bufferSize As Integer _) As FileStream

In both cases, the File.Create() method returns a Stream value, in this case a FileStream value.As the File.Create() method indicates, it takes the name or path of the file as argument. If youknow or want to specify the size, in bytes, of the file, you can use the second version.

To provide the same operation of creating a file, you can use the Open() method of the File class.It is overloaded in three versions as follows:

Overloads Public Shared Function Open( _ ByVal path As String, _ ByVal mode As FileMode _) As FileStreamOverloads Public Shared Function Open( _ ByVal path As String, _ ByVal mode As FileMode, _ ByVal access As FileAccess _) As FileStreamOverloads Public Shared Function Open( _ ByVal path As String, _ ByVal mode As FileMode, _ ByVal access As FileAccess, _ ByVal share As FileShare _) As FileStream

File Information

Introduction

In its high level of support for file processing, the .NET Framework provides the FileInfo class.This class is equipped to handle all types of file-related operations including creating, copying,moving, renaming, or deleting a file. FileInfo is based on the FileSystemInfo class that providesinformation on characteristics of a file.

File Initialization

The FileInfo class is equipped with one constructor whose syntax is:

Public Sub New(ByVal fileName As String)

This constructor takes as argument the name of a file or its complete path. If you provide only thename of the file, the compiler would consider the same directory of its project. Here is anexample:

Dim fleMembers As FileInfo = new FileInfo("First.txt")

Alternatively, if you want, you can provide any valid directory you have access to. In this case, youshould provide the complete path.

File Creation

The FileInfo constructor is mostly meant only to indicate that you want to use a file, whether itexists already or it would be created. Based on this, if you execute an application that has only aFileInfo object created using the constructor as done above, nothing would happen.

To create a file, you have various alternatives. If you want to create one without writing anythingin it, which implies creating an empty file, you can call the FileInfo.Create() method. Its syntaxis:

Page 483: Microsoft Visual Basic 2010 Tutorial

Public Function Create() As FileStream

This method simply creates an empty file. Here is an example of calling it:

dim fleMembers as FileInfo = new FileInfo("First.txt")fleMembers.Create()

The FileInfo.Create() method returns a FileStream object. You can use this returned value towrite any type of value into the file, including text. If you want to create a file that contains text,an alternative is to call the FileInfo.CreateText() method. Its syntax is:

Public Function CreateText() As StreamWriter

This method directly returns a StreamWriter object. You can use this returned object to writetext to the file.

File Existence

When you call the FileInfo.Create() or the FileInfo.CreateText() method, if the file passed asargument, or as the file in the path of the argument, exists already, it would be deleted and a newone would be created with the same name. This can cause the right file to be deleted. Therefore,before creating a file, you may need to check whether it exists already. To do this, you can checkthe value of the Boolean FileInfo.Exists property. This property holds a true value if the fileexists already and it holds a false value if the file doesn't exist or it doesn't exist in the path.

Here is an example of checking the existence of a file:

Dim fleMembers As FileInfo = new FileInfo("First.txt")fleMembers.Create()

If fleMembers.Exists = True Then Exit Sub

Writing to a File

As mentioned earlier, the FileInfo.Create() method returns a FileStream object. You can usethis to specify the type of operation that would be allowed on the file.

To write normal text to a file, you can first call the FileInfo.CreateText() method. This methodreturns a StreamWriter object. The StreamWriter class is based on the TextWriter class that isequipped with Write() and WriteLine() methods used to write values to a file. The Write()method writes text on a line and keeps the caret on the same line. The WriteLine() methodwrites a line of text and moves the caret to the next line.

After writing to a file, you should close the StreamWriter object to free the resources it wasusing during its operation(s).

Appending to a File

You may have created a text-based file and written to it. If you open such a file and find out thata piece of information is missing, you can add that information to the end of the file. To do this,you can call the FileInfo.AppenText() method. Its syntax is:

Public Function AppendText() As StreamWriter

When calling this method, you can retrieve the StreamWriter object that it returns, then use thatobject to add new information to the file.

Operations on Files

Opening a File

As opposed to creating a file, probably the second most regular operation performed on a fileconsists of opening it to read or explore its contents. To support opening a file, the FileInfo classis equipped with the Open() method that is overloaded with three versions.

If you have a text-based file and want to directly read from it, you can use the StreamReaderclass that is equipped with Read() and ReadLine() methods. As done for the StreamWriterclass, after using a StreamReader object, make sure you close it.

Deleting a File

If you have an existing file you don't need anymore, you can delete it. This operation can beperformed by calling the FileInfo.Delete() method. Its syntax is:

Overrides Public Sub Delete()

Here is an example:

Page 484: Microsoft Visual Basic 2010 Tutorial

Dim fleMembers As FileInfo = new FileInfo("First.txt")fleMembers.Delete()

Copying a File

You can make a copy of a file from one directory to another. To do this, you can call theFileInfo.CopyTo() method that is overloaded with two versions. The first version has thefollowing syntax:

Overloads Public Function CopyTo(ByVal destFileName As String)As FileInfo

When calling this method, specify the path or directory that will be the destination of the copiedfile. Here is an example:

Dim fleMembers As FileInfo = new FileInfo("Reality.txt")Dim strMyDocuments as string = _ Environment.GetFolderPath(Environment.SpecialFolder.Personal)fleMembers.CopyTo(String.Concat(strMyDocuments, "\\Federal.txt"))

In this example, a file named Reality.txt in the directory of the project would be retrieved and itscontent would be applied to a new file named Federal.txt created in the My Documents folder ofthe local computer.

When calling the first version of the FileInfo.CopyTo() method, if the file exists already, theoperation would not continue and you would simply receive a message box. If you insist, you canoverwrite the target file. To do this, you can use the second version of this method. Its syntax is:

Overloads Public Function CopyTo( _ ByVal destFileName As String, _ ByVal overwrite As Boolean _) As FileInfo

The first argument is the same as that of the first version of the method. The second argumentspecifies what action to take if the file exists already in the target directory. If you want tooverwrite it, pass the argument as true otherwise, pass it as false.

Moving a File

If you copy a file from one directory to another, you would have two copies of the same file or thesame contents in two files. Instead of copying, if you want, you can simply move the file from onedirectory to another. This operation can be performed by calling the FileInfo.MoveTo() method.Its syntax is:

Public Sub MoveTo(ByVal destFileName As String)

The argument to this method is the same as that of the CopyTo() method. After executing thismethod, the FileInfo object would be moved to the destFileName path.

Here is an example:

Dim fleMembers As FileInfo = new FileInfo("pop.txt")Dim strMyDocuments As String = _ Environment.GetFolderPath(Environment.SpecialFolder.Personal)fleMembers.CopyTo(String.Concat(strMyDocuments, "\\pop.txt"))

Characteristics of a File

The Date and Time a File Was Created

To keep track of it, after a file has been created, the operating system makes a note of the dateand the time the file was created. This information can be valuable in other operations such assearch routines. You too are allowed to change this date and time values to those you prefer.

As mentioned already, the OS makes sure to keep track of the date and time a file was created.To find out what those date and time values are, you can access theFileSystemInfo.get_CreationTime() property is. This would be done as follows:

Dim dteCreationTime As DateTime = fleLoan.CreationTimeConsole.WriteLine("Date and Time Created: {0}", dteCreationTime.ToString())

Of course, by entering the appropriate format in the parentheses of the ToString() method, youcan get only either the date or only the time.

If you don't like the date, the time, or both, that the OS would have set when the file wascreated, you can change them. To change one or both of these values, you can assign a desiredDateTime object to the FileSystemInfo.set_CreationTime() property.

The Date and Time a File Was Last Accessed

Many applications allow a user to open an existing file and to modify it. When people work in ateam or when a particular file is regularly opened, at one particular time, you may want to knowthe date and time that the file was last accessed. To get this information, you can access the

Page 485: Microsoft Visual Basic 2010 Tutorial

FileSystemInfo.LastAccessTime property.

If you are interested in know the last date and time a file was modified, you can get the value ofits FileSystemInfo.LastWriteTime property. You can also change this value if you want to makesure the file holds your own.

The Name of a File

The operating system requires that each file have a name. In fact, the name must be specifiedwhen creating a file. This allows the OS to catalogue the computer files. This also allows you tolocate or identify a particular file you need.

When reviewing or opening a file, to get its name, the FileInfo class is equipped with the Nameproperty. Here is an example:

Console.WriteLine("The name of this file is: """ & fleLoan.Name & """)

This as string simply identifies a file.

The Extension of a File

With the advent of Windows 95 and later, the user doesn't have to specify the extension of a filewhen creating it. Because of the type of confusions that this can lead to, most applications assistthe user with this detail. For example, when we implemented the routines that allow the user tosave or open a file, we specified a default extension for the Save Dialog or the Open Dialogobjects. This allows the user not to care for the extension. Based on this, some applications allowthe user to choose among various extensions. For example, using Notepad, a user can open a text,a PHP, a script, or an HTML file.

When you access a file or when the user opens one, to know the extension of the file, you canaccess the value of the FileSystemInfo.Extension property. Here is an example:

Console.WriteLine("File Extension: {0}", fleLoan.Extension)

The Size of a File

One of the routine operations the operating system performs consists of calculation the size of filesit holds. This information is provided in terms of bits, kilobits, or kilobytes. To get the size of a file,the FileInfo class is quipped with the Length property. Here is an example of accessing it:

Console.WriteLine("File Size: " & CStr(fleLoan.Length))

The Path to a File

Besides the name of the file, it must be located somewhere. The location of a file is referred to asits path or directory. The FileInfo class represents this path as the DirectoryName property.Therefore, if a file has already been created, to get its path, you can access the value of theFileInfo.DirectoryName property.

Besides the FileInfo.Directoryname, to know the full path to a file, you can access itsFileSystemInfo.FullName property.

The Attributes of a File

Attributes are characteristics that apply to a file, defining what can be done or must be disallowedon it. The Attributes are primarily defined by, and in, the operating system, mostly when a file iscreated. When the user accessed or open a file, to get its attributes, you can access the value ofits FileSystemInfo.get_Attributes() property. This property produces a FileAttributes object.

When you create or access a file, you can specify or change some of the attributes. To do this, youcan a FileAttributes object and assign it to the FileSystemInfo.set_Attributes() property.

FileAttributes is an enumerator with the following members: Archive, Compressed, Device,Directory, Encrypted, Hidden, Normal, NotContentIndexed, Offline, ReadOnly,ReparsePoint, SparseFile, System, and Temporary.

Previous Copyright © 2009-2010 FunctionX, Inc. Home