Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Microsoft Visual Basic 2010 Tutorial

Download as pdf or txt
Download as pdf or txt
You are on page 1of 485

Created by www.ebooktutorials.blogspot.

in
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
Introduction to Procedures Arguments and Parameters Introduction to Built-In Functions Static Variables Optional Arguments Overloading a Procedure

Built-In Functions
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
Introduction to Classes The Methods of a Class Class Construction and Destruction Structures

Topics on Classes
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


Inheritance Polymorphism Class Abstraction

Built-In Classes
Object Random

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

Introduction to Microsoft Visual Studio


MSVB
Introduction
Microsoft Visual Basic is a computer programming environement used to create graphical applications for the Microsoft Windows family of operating systems. It uses a computer language of the same name. Like every computer language, Visual Basic is used to give instructions 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 that make it easy to work on projects, to create the necessary files, and to distribute a completed application. To follow our lessons, you can use Microsoft Visual Studio 2010 or Microsoft Visual Basic 2010 Express. To get Microsoft Visual Basic 2010 Express, get to the Microsoft web site and click the 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 Visual Studio 2010.

The Microsoft Visual Studio Interface


The Main Menu
The top section of Microsoft Visual Studio displays the main menu divided in categories such as File 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 the Standard toolbar as its default. Some additional toolbars will display in response to an action

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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 menu category on the main menu by adding a menu item to it. You can customize a toolbar by adding a button to it. To start, right-click anything on the main menu or on any toolbar and click Customize... For example, imagine you want to add an item named Start Without Debugging to the 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:

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

f. Click Add Command... g. h. In the Categories list of the Add Command dialog box, select the category that has the button you want. For our example, that would be Debug In the Commands list, click the desired button or menu item. For our example, that would be Start Without Debugging

i. After makiing the selection, click OK

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

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 Express when it has been launched. It starts on top with a tab labeled Start Page. The main body of Microsoft Visual Basic Express displays Microsoft Visual Basic 2010 Express. The left section shows two labels: New Project... and Open Project... When some projects have been previously created or used, their names appear under Open Project... When you work on a project, the Start Page is usually in the background but it is represented by a tab. At any time, to display the 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 the most regularly used windows. If you think that one of them is not regularly used in your types of assignments, you can remove it from the screen. To hide a window, you can click its Close . button All of the windows you can use are listed in the View menu. Therefore, if a window is not displaying, you can click View on the main menu and click a window of your choice.

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

Auto Hiding a Window


When working on a project, you will use a set of windows that each accomplishes a specific purpose. Some windows are represented by an icon but hide the rest of the body. To display such 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 is called Auto Hide:

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

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

By default, the studio installs some windows to the left and some others to the right of the screen. You can change this arrangement if you want. To do this, expand a window, then click its title bar and start dragging. While you are dragging, to assist you with a new position, the studio 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 that side. When you get to a side, a transparent blue rectangle would be drawn to indicate the possible position. Drop the window to either the most left guiding box to position it to the left of the screen, or to the most right guiding box to position it to the right of the screen. Here is an example:

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

or

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

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

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 the existing window. Drop it in the This

Becomes

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

Floating Windows
Most of the windows you will use are positioned on one side of the screen. If you want, you can have a window that stays on top of other windows but is not "glued" to one side. Such a window is said to float. To float a window, drag its title bar and release it somewhere in the middle of the screen but not on a guiding box. on the title bar. If you click this When a window is floating, it displays a Maximize button button, the window occupies the whole interface of Microsoft Visual Studio. In the same way, if you 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:

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

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 title bar of the window that will share the area to its target until the bottom part of the base window shows a highlighted and a non highlighted area:

Then release the mouse:

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

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 window to 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

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

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 area with it. There are two ways yon do it You can drag a window and drop it on the tab of the Start Page.
This

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

becomes this

If a window is already represented with a tab on top of the Code Editor, you can drag the second window 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

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

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 functional language 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 that can understand and use the .NET Framework. Microsoft Visual Basic is used to create graphical applications, also referred to as Graphical User Interface (GUI) applications, web-based applications, 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 the Microsoft Visual Basic programming environment.

Introduction to Projects
The primary job of an application is to show its results on the monitor. A console application is one that displays its results in a black window referred to as a DOS window. In some of our lessons, we will create those types of applications. The Visual Basic language provides a rectangular object called a message box. If you create a Visual Basic application, you can display 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 Visual Basic 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 a source file. A source file that contains Visual Basic instructions is a regular, simple, ASCII, text-based file. 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

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

8. Click Save

Introduction to Modules
In Visual Basic source file, you write code as we will learn throughout our lessons. The code that is conform to the Visual Basic language is included in a section known as the module. This section starts with the Module keyword followed by a name and ends with the End Module expression. Everything between 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
Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
A procedure is a section of code that takes care of a specific task. In a module, the basic formula of a procedure is: Sub ProcedureName() End Sub Notice that it ends with the End Sub line. Because a module holds the code of a Visual Basic program, a procedure is included inside the start and the end of the module section. This would be done 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 in Visual Basic is called Main. In a program, the Main procedure is the entry point. That is where the program starts. Another common procedure highly used in Visual Basic is called MsgBox. As its name indicates, the MsgBox procedure is used to display a message in a dialog box. To make this happen, you can include the message inside the parentheses of MsgBox. The message itself should be included in double-quotes. An example would be: MsgBox("Whatever") To distinguish a procedure from other items used in a program, we will sometimes write it followed by parentheses. 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 Sub End 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't understant it. The instructions must be translated in a language the computer can understand. That language 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 that accomplish various goals to get a functional program at the end. The end result is a program that can be executed in a computer other than the one you used to create the project. That final program is called an executable. Ae mentioned already, a compiler is a computer program made of internal other sub-programs. One of the sub-programs, in fact probably the first, of a compiler is called a parser. A parser "scans" a file that contains (part of) the program. It checks the syntax, keywords, unknown words, and some other routines. If the parser finds a problem, which could be anything, either it stops or it continues making a list of the mistakes it found. Then it displays this list to you to fix. Sometimes it would point to the exact line where the/a problem was found. Sometimes it would point to the line where the problem showed its impact although the problem may be found somewhere else. With experience, you will know 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 its result(s) to the compiler. The compiler calls another program called a linker. If the program contains just one file, the linker considers it. If the program contains more than one file, the linker considers them. The linker gathers some of the files that the compiler shipped with (those files that your program needs in order to work), puts them together ("links" them) with your file(s) to get your instructions in a manner that can produce a suitable result. If there is no significant problem, the compiler creates the executable. This doesn't mean that everything is alright, it only means that the

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
compiler thinks that everything is alright: it is still possible that the result may not be what you would expect. We will come back to these issues. To make your life easier, all of the sub-programs (parser, linker, debugger, etc) that ship with Visual Basic 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 machine language. Microsoft created and makes freely available a Visual Basic compiler you can use to create your applications. 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 create our 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 Framework installed in your computer already. By default, it is installed in C:\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 the compiler's path to the Path of the Environment Variables. To start, use a file utility such as Windows Explorer 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. Click System and Security:

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

In the System and Security section, click System:

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

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

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:

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

Click OK three times. Open the Command Prompt. Type CD\ and press Enter to move to the root drive. Type CD and a space, followed by the folder (and sub-folder(s)) where the file is located, and press Enter. To compile, 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 the file 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 followed by 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 is in one word, you can just type it. Here is an example: vbc /out:Welcome.exe Exercise.vb

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

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 compiling the project, you must remember to reference each file. To do that, in the last section, add the name of 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 to other people.

Executing a Program
After building the code, you and your users can execute it. If you are working from the Command Prompt, 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 execute an application, on the main menu, you can click Debug -> Start Debugging.

A Solution and its Projects


Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

Creating a Project
Although you can creat a complete and fully functional application using a text editor, Microsoft Visual Studio and Microsoft Visual Basic 2010 Express provide a graphical environment that is more convenient. 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 you want to create a new solution too, and you must give it a name. By default, the new project and solution would hold the same name. If you accept the suggestions, you would get a main folder with 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 of the 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 Console Application. Change the Name to GeneralCensus

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

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 access the 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 is equipped with a title bar that displays its name on the left side and three buttons on the right side: 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 is disabled if the window is already floating. If the window is docked and you click Float, it would be 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:

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

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 of the 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 that are part of the current project. To expand a node, you can either click its button or double-click its name. 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 the solution. Inside of the project are its folders, files, and resources. The first item under a project name is References. After the References node, there are the names of the classes that are part of the 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 used in 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 for the Solution Explorer. To show the operating system's characteristics of a project or a file, in the Solution Explorer, click the 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 its location (in the Full Path) field The Properties window displays different fields depending on the item selected in the Solution Explorer. You can change some things in the Properties window. When a field is disabled, it means you cannot modify it.

Managing a Solution
Introduction
Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
A solution is used to coordinate the different aspects of an application that is being created. When you have created a project, 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 Visual Studio selects your personal directory as the path to the solution. This is called the location. In the location, Microsoft Visual 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 the solution, you can change the string in the Solution Name text box. Remember that you can enter the name of the project in 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 the Documents\Visual Studio 2010\Projects folder. It uses the name of the solution to name the folder. It creates some files and stores them in that new folder. Then, it creates a sub-folder, using the name of the project, inside of the folder of the solution. Besides the sub-folder with the name as the project, it creates another folder named debug. It also creates another folder named Debug in the sub-folder of the name of the project. In each folder and some other folders, it creates 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 click File -> Save solution-name.sln As... This would bring the Save File As dialog box where you can specify the name of the solution and click Save.

Renaming a Solution

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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, locate the 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. When Microsoft Visual Studio 2010 (any edition) is installed, it creates a folder named Visual Studio 2010 in your Documents folder. The Documents folder is called your personal drive or your personal directory. Inside of the Visual Studio 2010 folder, it creates a sub-folder named Projects. By default, this is where it would save your projects, each with its own folder.

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
To save a project, on the Standard toolbar, you can click the Save All button . Alternatively, on the main menu, you can click File -> Save All. If the project had already been saved but you want to save it under a different name, on the main 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 add another 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 or change 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 new name 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 files continuously as you see fit. If you are using Microsoft Visual C# 2010 Express or Microsoft Visual Studio, to add a new file to 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 are examples:

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

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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 mouse on 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. Locate the 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 can click File -> Open... If you are trying to open a source file, first change the file type combo box to All Files (*). Then locate 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 that holds 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 Solution Explorer, 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

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

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 skeleton codes you can use and customize. It writes the primary code for you and add all the necessary default behaviors. Once it has done this, you can change or remove any section. To access these code skeletons, in the section of the file where you want to add it, right-click and click Insert Snippet...:

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

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. The Code Editor provides some skeleton codes you can use. To use this approach, right-click the code you want to modify and click 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

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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 application using 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 Startup Object 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 common readable 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 the Options dialog box, in the Environment section, click Fonts and Colors. To set the color of a category, in the Display Items section, click the category. In the Item Foreground combo box, select the desired color. If you want the words of the category 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 to display 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 code by category. To delimit the items of your code, you should indent them by two empty spaces or one tab. Indentation should be incremental. That is, when a line of code appears to be a child of the previous line, the new line should be indented.

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
To control the indentation of your code, on the main menu, click Tools -> Options... In the left list, Text Editor amd expand 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 any way you want. In the Visual Basic language, the line that contains a comment can start with a single quote. Here is an example: Module Module1 Sub Main() ' This line will not be considered as part of the code End Sub End Module

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
Alternatively, you can start a comment with the Rem keyword. Anything on the right side of rem, Rem, or REM would not 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 and they do not increase the size of your application. Comments can help you and other people who read your code to figure out what a particular section of code is used for, which can be helpful when you re-visit your code after months or years of 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 is referred to as white space. The amount of space you put between two words is not important. The compiler would ignore the white spaces between words. This means that Sub Main() and Sub Main() would the same effect. In the same way Sub Main() and Sub would produce the same effect. Main()

Previous

Copyright 2008-2010 FunctionX

Next

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

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. At other 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 computer uses its memory. The computer memory is an area used to receive information, store it, and then make that information 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 program might be made for names. Because the information stored in the computer can be as varied as possible, it may be segmented (the word segment is taken in its English meaning and not in its Assembly definition) in portions or various pieces. The pieces of information stored in the computer memory come, go, and change on a regular basis. For this reason, a piece of information stored in the computer memory is called a variable. A variable is an area of the computer memory used to store a value. Because there can be many kinds of values stored in the computer memory, a variable stores only one kind of value.

The Stack
To manage the various types of values that can be used in a program, the computer is equipped with two types of memory. The Random Access Memory, also called RAM, is a type of memory that is "filled" with values when the computer comes up and while a person is using the computer. When the computer gets shut down, the RAM looses everything that was put in that memory so that the next time the computer comes up, the RAM "forgets" the values that were entered in it the previous time. In other words, when the computer boots up, the RAM is empty and new values must be entered in it. Another type of memory that the computer uses is called Read-Only Memory (ROM). In this area, the computer stores values that "stick" in it and stay there. Such values can be called when needed and, unless they are explicitly deleted, when the computer gets shut down, the values go back to the ROM. The next time the computer comes up, the values of the ROM will be 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 while the 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 our illustrations, when the box is empty, the bit has a value of 0. When it is filled (it cannot be halffull 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

Content downloaded from www.functionx.com

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

When your application comes up, you can ask the computer to put some values for your application. Remember that you are not, or your application is not, the only one that needs to use an area of the computer memory. Because there can be so many values that different applications store, retrieve, and manipulate all day long or as long as the computer is on, the operating system reserves an area of this memory for applications like yours. To make sure there is no mess, the computer is in charge of this area of memory. When you want to store a value 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, decides where to put the value). When the value is not used anymore, the computer removes (the verb used is "pop") that value. This allows the computer to make that area of memory available to the applications that would need it. This area of memory that the computer reserves for the various 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 a value 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 must first type the Dim keyword: Dim To make this request, you must provide a name for the variable. The name of a variable is also called an identifier. When the computer reserves an area of memory, it uses a name to be able to locate that area of memory. Later on, when you want to store a value in that memory, you will communicate a name to the compiler. The compiler will know the area of memory you are referring to by its name. This means that, at the right time, the name is used by both you and the compiler to know what portion of memory you are referring to. The name itself is not stored in the memory per se. It only allows you and the compiler to access a particular area of memory.

The Name of a Variable


There are rules you should, and usually must, follow when naming your variables. The rules to follow 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 as the 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 64 characters)

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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. These words 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 should avoid): AddHandler Ansi ByRef Catch CDbl CLng CSByte CUInt Decimal DirectCast Else End Error Finally Get Group By Imports Into Join Long Module Namespace Nothing Off Or Overrides Property ReDim SByte Short Step Sub Then TryCast UShort Went With AddressOf As Byte CBool CDec CObj CShort CULng Declare Distinct ElseIf EndIf Event For GetType Group Join In Is Key Loop MustInherit Narrowing NotInheritable On Order By ParamArray Protected REM Select Single Stop SyncLock Throw TypeOf Until When WithEvents Enum Exit Friend GetXmlNamespace Handles Inherits IsFalse Let Me MustOverride New NotOverridable Operator OrElse Partial Public RemoveHandler Set Skip Strict Take To UInteger Using Where WriteOnly Equals Explicit From GoSub If Integer IsNot Lib Mid MyBase Next Object Option Overloads Preserve RaiseEvent Resume Shadows Skip While String Take While True ULong Variant While Xor Widening Erase False Function GoTo Implements Interface IsTrue Like Mod MyClass Not Of Optional Overridable Private ReadOnly Return Shared Static Structure Text Try Unicode Alias Assembly ByVal CByte Char Compare CSng CUShort Default Do And Auto Call CChar CInt Const CStr Custom Delegate Double AndAlso Boolean Case CDate Class Continue CType Date Dim Each

Although you must always avoid using keywords as names of your variables in your program, if you insist on using one of these keywords to name something, put the word between square brackets. An example would be [True] The Visual Basic language is not case sensitive. This means that NAME, name, and Name represent the same word. This means that, in the same section (normally called scope), you cannot have two variables with the same name that differ only by their cases. This would cause a name conflict. If you declare a variable in a scope and use it later with a different case, as

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
long as the same characters are used on both names, the Visual Basic compiler would know what 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 use two variables that seem to be different but because of a mistype, you would think that you are using two variables. Examples are Type and Tape. To indicate to the compiler that each variable must be declared prior to being used, in the top section 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 called size, of memory that the variable would need. This is because different values use different amounts of space. For example, the title of a book certainly needs more space than the number of pages of a daily newspaper. The amount of space that a variable can occupy is referred to as its data type. To limit the amount of gymnastics to perform, the compiler uses categories of data types. For example, it can decide that a simple number would use one small "box" to store its value. On the other hand, 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 would need for a particular variable. You can do this by specifying the most appropriate category. After telling the compiler that this particular variable would be used to store a number, you can change it in the middle of the program and decide to store an employee's maiden name. On the other hand, some numbers will require more space than others. For example, imagine you want to store the population of countries in a variable. In this case you would request memory that can hold a large number. This type of variable must be able to hold the population of China as well as the population of Burundi. Of course, this same space can hold the number of pages of a daily 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 is better to have a few empty "buckets" in the computer memory than to have unavailable memory. To reduce the number of mistakes that could be due to a possible wrong value being stored in a variable, 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 2010 Express) 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


Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
We saw that, to declare a variable, you use the Dim keyword, followed by a name. Here is an example: 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 for that variable but there may be two possible (small) problems: the compiler does not know how much space that variable would need to store its values and, because of this, the compiler would leave empty that area of memory. To access the value of a variable, you can simply refer to its name. For example, you can display it to the user. We saw that you could use the MsgBox procedure to display a value. Here is 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 be stored in the memory area reserved for it. When you have declared a variable, the compiler gives it an initial value. This is referred to as initializing the variable. Instead of the compiler doing it, you too can initialize a variable. Initialization partially solves the two problems we mentioned. In reality, when you declare a variable, the compiler primarily considers it a string and reserves enough space to store any amount of characters. One way you can solve this confusion is to initialize the variable. To initialize a variable, type its name, followed by =, and followed by the desired value. Here is an 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 you initialize a variable, the compiler uses the given value to convert it to the appropriate type. For example, if you consider a variable with 25, it becomes considered an integral variable; that is, a variable whose memory can hold natural numbers.

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
We mentioned that, after declaring a variable, you could change its value whenever you judge it necessary. After declaring a variable as done in the above example, you can assign it any value of 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 are used to request values from the user. To make this possible and easy, Visual Basic provides a procedure called InputBox. To use it, type it, followed by parentheses. In its parentheses, enter a sentence that will serve as a guide to the user. The sentence itself should be included between double-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 the user's value. Here is an example:

The user is expected to type a value in the text box. As mentioned for the variables, the value the user types is primarily considered a regular series of characters. To use that series, you must convert it to the appropriate type. We will review the procedures used to convert the values. 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 to produce a new value by combining existing values. Therefore, an operation is performed using at least one symbol and one value. The symbol used in an operation is called an operator. A variable 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: _


Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
If you plan to write a long piece of code, to make it easier to read, you may need to divide it in various 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 an alternative, you can use the line continuation operator represented by a white space followed by an 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 to create sections in an operation. This regularly occurs when more than one operators are used in an 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 result by 5 or you want to multiply 3 by 5 and then add the result to 8. Parentheses allow you to specify 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 the result 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 involves various operators. This concept is based on a theory called operator precedence. This theory manages which operation would execute before which one; but parentheses allow you to completely 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 to delimit 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 a method. 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 give the copy to another variable. The assignment operation is performed with the = sign.

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
After you have declared a variable, before using it, it must have a value. One way you can give a 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 ever is inside the double-quotes is the thing that need to be delimited. The value inside the doublequotes 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, we will 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: Enter Customer Acnt #: Enter Initial Deposit: Gertrude Monay 92-37293-30 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. The Visual Basic language allows you to write as many statements as necessary on the same line. To do 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

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

String Concatenation: &


The & operator is used to append two strings or expressions. This is considered as concatenating them. For example, it could allow you to concatenate a first name and a last name, producing a full 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 a concatenated 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 & LastName End Sub To concatenate more than two expressions, you can use as many & operators between any two strings or expressions as necessary. After concatenating the expressions or values, you can assign 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 programming environment

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 sections as 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:")

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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, to create a tab white space, you can press the Tab key. If you want to get the same effect in the results you present to the user, you can use the vbTab operator of the Visual Basic language. Here are examples:

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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. The numbers on the left side of the 0 are referred to as negative while the numbers on the right side of the rulers are considered positive: - - -6 -6 -5 -5 -4 -4 -3 -3 -2 -2 -1 0 -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, you can write a + sign on its left. Examples are +4, +228, +90335. In this case the + symbol is called 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. 1 2 3 4 5 6 +

The Negative Operator As you can see on the above ruler, in order to express any number on the left side of 0, it must be appended with a sign, namely the - symbol. Examples are -12, -448, -32706. A value accompanied 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, whenever a number is negative, it MUST have a - sign. In the same way, if you want to change a value from positive to negative, you can just add a - sign to its left.

Arithmetic Operators
Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

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 + TuesdayHours to 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, to add one string to another. This is done by appending one string at the end of another. Here is an example: Module Exercise Sub Main() Dim FirstName Dim LastName Dim FullName FirstName = "James " LastName = "Fame" FullName = FirstName + LastName MsgBox("Full Name: " & FullName) End Sub End 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 "Customer Name: " "Account Number: " "Total Deposits: $" MsgBox(Result) End Sub End Module 2. To execute the application, press F5 3. After using the program, return to your programming environment Bank =-=" & vbCrLf & & CustomerName & vbCrLf & & AccountNumber & vbCrLf & & (InitialDeposit + RegularDeposit)

Multiplication *
The multiplication operation allows you to add a number to itself a certain number of times set by another number. The multiplication operation is performed using the * sign. For example, to add 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 difference of two or more numbers. It could also be used to display a number as a negative value. To subtract 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


Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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 is used to get the fraction of one number in terms of another. Microsoft Visual Basic provides two types of operations for the division. If you want the result of the operation to be a natural number, 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 ^
Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
Exponentiation is the ability to raise a number to the power of another number. This operation is 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, but they must carry valid values that can be evaluated. When the operation is performed, the value of 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 in some circumstances. Sometimes you will want to get the value remaining after a division renders 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 be involved in another operation or expression.

Bit Operations
Introduction
From our introduction to variables, you may remember that the computer stores its data in memory 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 or 0. Bit manipulation consists of changing the value (1 or 0, or 0 or 1) in a box. As we will see in the next few operations, it is not just about changing a value. It can involve reversing a value or 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 is decimal 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 hardly perform 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 we were 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 to 0. If it contains 0, you can reverse it to 1. To support this operation, the Visual Basic language provides the Not Operator. As an example, consider the number 286. The decimal number 286 converted to binary is 100011110. You can reverse each bit as follows:

Content downloaded from www.functionx.com

286

Created by www.ebooktutorials.blogspot.in
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 another box (a bit). To support the bitwise conjunction operation, the Visual Basic language provides the And operator. To perform the bit addition on two numbers, remember that they must be converted to binary first. Then: If a bit with value 0 is added to a bit with value 0, the result is 0 Bit0 Bit1 Bit0 And Bit1 0 0 0

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

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

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

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

Therefore, 286 And 4075 produces 100001010 which is equivalent to: Bit8 256 286 And 4075 1 256 Bit7 128 0 0 Bit6 64 0 0 Bit5 32 0 0 Bit4 16 0 0 Bit3 8 1 8 Bit2 4 0 0 Bit1 2 1 2 Bit0 1 0 0

This means that 286 And 4075 = 256 + 16 + 2 = 266 This can also be programmatically calculated as follows:

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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 to binary first. Then: If a bit with value 0 is added to a bit with value 0, the result is 0 Bit0 Bit1 Bit0 Or Bit1 0 0 0

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

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

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

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

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
Therefore, 305 Or 2853 produces 101100110101 which is equivalent to: Bit11 2048 305 Or 2853 1 2048 Bit10 1024 0 0 Bit9 512 1 512 Bit8 256 1 256 Bit7 128 0 0 Bit6 64 0 0 Bit5 32 1 32 Bit4 16 1 16 Bit3 8 0 0 Bit2 4 1 4 Bit1 2 0 0 Bit0 1 1 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 bitwise exclusion, the Visual Basic language provides an operator named Xor: If both bits have the same value, the result is 0 Bit0 Bit1 Bit0 Xor Bit1 0 0 0 1 1 0

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

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

Therefore, 305 Or 2853 produces 101110011110 which is equivalent to: Bit11 Bit10 Bit9 Bit8 Bit7 Bit6 Bit5 Bit4 Bit3 Bit2 Bit1 Bit0

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
2048 618 Xor 2548 1 2048 1024 0 0 512 256 128 1 1 1 512 256 128 64 0 0 32 0 0 16 1 16 8 1 8 4 1 4 2 1 2 1 0 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 ore more bits. Once again, to perform this operation, the number has to be converted to its binary equivalent. To support this operation, the Visual Basic language provides an operator represented as <<. Imagine you have a number as 741. Its binary equivalent is 1011100101 and can be represented 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 push each bit to the left by one position. Actually, you consider the bit at position x and the bit to its left at position y. You replace the value of Bit y by the value of Bit x. If Bit x is the most right bit, it receives a value of 0. This can be illustrated as follows: Original << by 1 1 1 0 0 1 1 1 1 1 1 0 0 0 0 1 1 0 0 1 1 0

As a result, we get 10111001010. The decimal result can be calculated as follows: Bit10 1024 741 << 1 1 1024 Bit9 512 0 0 Bit8 256 1 256 Bit7 128 1 128 Bit6 64 1 64 Bit5 32 0 0 Bit4 16 0 0 Bit3 8 1 8 Bit2 4 0 0 Bit1 2 1 2 Bit0 1 0 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))

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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 in reverse 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 -> Close Project (Microsoft Visual Basic 2010 Express) 2. When asked whether you want to save, click Discard

Previous

Copyright 2008-2010 FunctionX

Next

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

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, the value is primarily considered a normal group of characters, also called a string. If you intend to 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 are going 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's name, you type the As keyword followed by the data type. The formula to declare such a variable is: Dim VariableName As DataType

Type Characters
To make variable declaration a little faster and even convenient, you can replace the As DataType expression with a special character that represent the intended data type. Such a character is called a type character and it depends on the data type you intend to apply to a variable. When used, the type character must be the last character of the name of the variable. 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, except those added to make it easier to read. Examples of natural numbers are 122 and 2864347. When a natural number is too long, such 3253754343, to make it easier to read, the thousands are separated by a special character. This character depends on the language or group of languages and it is called the thousands separator. For US English, this character is the comma. The thousands separator symbol is used only to make the number easier to read. You will never 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

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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 combinations of 8 bits is 2 7 + 2 6 + 2 5 + 2 4 + 2 3 + 2 2 + 2 1 + 2 0 = 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 255. Since all bits can have values of 0 each, a byte can have values from 0 to 255. Therefore, a byte can hold a small natural positive number 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. To convert a value to a Byte value, you can use CByte(). To do this, enter the value or the expression in the parentheses of 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 an alternative. A signed byte is a small number that is between -127 and 128. To declare a variable for such a number,

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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, the age of a person. To declare a variable that can hold natural numbers in the range of -32768 to 32767, you can use the Short 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 necessary value 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 Short value. To indicate that the number must be treated as a Short and not another type of value, type s or S on the right of 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 parentheses of 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

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
that must be positive, you must store it as an unsigned short integer. An unsigned short integer is a natural number between 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 would produce:

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 data type to declare it. A variable declared with the Integer data type can hold a value between -2,147,483,648 and 2,147,483,647. Here is an example: Module Exercise Sub Main() Dim NumberOfPages As Integer End Sub

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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 the conversion 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 the necessary value but you have three or four alternatives. To initialize the variable with a regular natural number, you can 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 is an 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 of representing 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 still allows you to represent any natural number. To initialize an integer variable with a hexadecimal number, start the value with &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:

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
Besides the regular natural or the hexadecimal numbers, the third type of value an Integer variable can hold is referred 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. If you want the number to only be positive, you can declare it as an unsigned integer. An unsigned integer is a number between 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 the parentheses. 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 and 9,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 declare a 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

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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 with the 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 a decimal, 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 large number but the number but be positive, you can consider it as an unsigned long integer. Such a number can be between 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

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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 separated by 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 the Regional (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 the right 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 not important. In the Visual Basic language, such a number has a value that can range from -3.402823e 38 and -1.401298e 45 if the number is negative, or 1.401298e -45 and 3.402823e 38 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:

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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 the word 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 value is more suitable for another type as we will see in the next section. Otherwise, to indicate that the variable must be treated 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(). If the 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 larger number, Visual Basic provides the Double data type. This is used for a variable that would hold numbers that range from 1.79769313486231e 308 to 4.94065645841247e 324 if the number is negative 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 the Double keyword. In most circumstances, it is preferable to use Double instead of Single when declaring a variable that would hold a decimal number. Although the Double takes more memory spaces (computer memory is not expensive anymore(!)), it provides more precision.

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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 a Double 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 can initialize 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 its right 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 the expression 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 #:")

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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:

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

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 values that can be stored in a combination of 128 bits. You declare such a variable using the Decimal keyword. The values stored in a decimal variable can range from 1.0 x 1028 to 7.9 x 10 28 with a precision of 28 to 29 digits. Because of this high level of precision, the Decimal data type is suitable for currency values. Like those of the other numeric types, by default, a variable declared as Decimal is initialized with 0. After declaring a decimal variable, you can initialize it with a natural number. To indicate to the compiler to reserve space enough to store a decimal value, add a d or D to the right side of the value. 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 empty character. Otherwise, after declaring a Char variable, you can initialize it with a single character included 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 can type c or C on the right side of the double-quoted value. Here is an example: Module Exercise

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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 a string 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 string variable. 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 between double 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 an example: 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 its parentheses. If the value is an appropriate date or time, CStr() would produces a string that represents that date or that time value.

Practical Learning: Using Strings


Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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 a determined period. A time is a numeric value that represents the number of seconds that have elapsed in a day. To declare a variable that can hold either date values, time values, or both, you can use the Date data type. After the variable has been declared, you will configure it to the appropriate value. Here are two examples: Module Exercise Sub Main() Dim DateOfBirth As Date Dim KickOffTime As Date End Sub End 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 in the Regional Settings Properties of the Control Panel of the computer on which the application is run. The rules for the dates are defined in the Date property page:

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

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 because the application will refer to them when it is installed in someone else's computer.

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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 and time 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 set to 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 would be 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 in the 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:")

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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 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 as 2

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

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

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, but sparingly, 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 use the Object data type. As you can see from the result of the above program, the vbc compiler knows how to convert the value of any Object variable to the appropriate type. On the other hand, 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 -> Close Project (Microsoft Visual Basic 2010 Express) 2. When asked whether you want to save, click Discard

Previous

Copyright 2008-2010 FunctionX

Next

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

Using Variables
Constants
Introduction
A constant is a value that doesn't change. There are two types of constants you will use in your 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 for the variable, followed by the assignment operator "=", and followed by the value that the constant will hold. Here is an example:

Module Exercise Sub Main() Const DateOfBirth = #12/5/1974# MsgBox(DateOfBirth) End Sub End Module When defining a constant like this, the compiler would know the type of data to apply to the variable. 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 keyword and 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 Sub End Module When creating a constant, if its value supports a type character, instead of using the As keyword, you can use that type 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. Because there 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

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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 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 13. Enter values as follows: Customer Name: Jeannette Sharma to close the Property Pages window

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

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
Customer Phone: Order Date: Order Time Number of Shirts: Number of Pants: (301) 218-9000 04/11/2008 08:24 6 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 to initialize 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 its type. 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 variables outside 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 be accessed by another part (such as another procedure) of the program.

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

Global Variables
A variable that is declared outside of any procedure is referred to as global. To declare a global variable, use the same formula as we have done so far. For example, just above the Sub Main() line, you can type Dim, followed by the name 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) of the same file. In most cases, a global variable must be declared inside of a module, that is, between the Module ModName and the End Module lines but outside of a procedure. Based on this, such a variable is said to have module scope because it is available to anything inside of that module.

Practical Learning: Declaring Global Constants


1. Change the document as follows: Module CleaningOrder Const Const Const Const UnitPriceShirts As Double = 1.25 UnitPricePants As Double = 1.95 UnitPriceOtherItems As Double = 3.25 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: Customer Phone: Order Date: Order Time Number of Shirts: Number of Pants: Shawn Nitty (301) 423-7744 04/11/2008 09:12 0 2

Number of Other Items: 0 4. Enter the amount tended as 20 5. Close the message box and return to your programming environment

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

Modules
Introduction
In the small programs we have created so far, we were using only one file. A typical application uses as many files as necessary. You can use one file to list some objects used in other files. As we move on, we will see different examples of 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 option of the New Project dialog box, Microsoft Visual Studio would create a default file for and would insert the module template code. To create a module in Microsoft Visual Studio or Microsoft Visual Basic 2008 Express Edition, on the main menu, you can click Project -> Add Module... This would display the Add New Item dialog box with the Module selected as default in the Templates list. The studio would also suggest a default name. You can accept that name or change it. The name of the module follows the rules of an object in the Visual Basic language. Once you are ready with the dialog box, you can click Add. If you are manually creating your code from Notepad or any text editor, you can simply create any file in your folder and 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 Module ModuleName 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 be inserted 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 rules you must follow. At a minimum, you can declare one or more variables in a module, just as we have done so far. Here is an example: Module Exercise Dim FullName As String End 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 module using 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 Windows menu. 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 and names it Module1. Of course, you can add as many modules as necessary. At any time, you can change the name of a module. To rename a module, in the Solution Explorer

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
Right-click the name of the module and click Rename. Type the desired name with the .vb extension and press Enter 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. You will 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. This allows different modules to exchange information. For example, if you are planning to use the same variable in more than section of your application, you can declare the variable in one module and access that variable in any other module 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 referred to 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 String End 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 String End Module

File 2: Exercise.vb Module Exercise Sub Main() FullName = "Gertrude Monay" MsgBox("Full Name: " & FullName) End Sub End 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 from other 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

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
End Module This would produce:

Practical Learning: Declaring Global Private Variables


1. Change the document as follows: Module CleaningOrder Const Const Const Const UnitPriceShirts As Double = 1.25 UnitPricePants As Double = 1.95 UnitPriceOtherItems As Double = 3.25 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: Customer Phone: Order Date: Order Time Number of Shirts: Number of Pants: Landry Kurtzmann (202) 223-3325 04/12/2008 07:35 8 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 from other 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

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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 Sub End 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 a member of a module has. In previous sections, we saw how to control the members of a module. The level of access of a module itself can also be controlled. To control the level of access of a module, you can precede the Module keyword with 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 the same application. The public members cannot be accessed outside of the same application. This means that if you create an application A that has a friend module M and that module contains a public variable V, that variable V cannot 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 friend members 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 other applications (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

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
3. Enter values as follows: Customer Name: Customer Phone: Order Date: Order Time Number of Shirts: Number of Pants: William Nessif (301) 220-3737 04/12/2008 08:26 3 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 Sub End Module It is important to know that different variables can be declared with the same data type as in the following example: Module Exercise Sub Main() Dim NumberOfPages As Integer Dim Category As Integer Dim MagazinePrice As Double End Sub End Module When two variables use the same data type, instead of declaring each on its own line, you can declare 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, and ending the line with the common data type:

Module Exercise Sub Main() Dim NumberOfPages, Category As Integer Dim MagazinePrice As Double End Sub End 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 As keyword. Then type a comma, followed by the other variable(s) and data type(s). Here is an example

Module Exercise Sub Main() Dim NumberOfPages, Category As Integer Dim CountryName As String, MagazinePrice As Double End Sub End Module
In this case, CountryName is a string variable while MagazinePrice is a Double variable

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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 you decide to specify its value. Whether such a variable has been initialized or not, at any time, you can 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 Main and 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 use the variable and what type of values the variable should hold. In some cases, you may want the variable to hold a constant value and not be able to change it. We saw earlier that such a variable could be declared as a constant. An alternative is to declare it with the ReadOnly keyword. While a constant variable can be declared locally, a ReadOnly variable cannot. It must be declared globally.

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
As done for a constant, when declaring a ReadOnly variable, you should initialize it. If you do not, the compiler would assign the default value based on its type. For example, a numberbased variable would be initialized with 0 and a String variable would be initialized with an empty string. As done so far, to initialize the variable, use the assignment operator followed by the desired value. Like a constant, after declaring and optionally initializing a ReadOnly variable, you cannot change 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 readonly variable when you try changing its value. A window named Error List would also point out the problems:

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

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 how to 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 dialog box where you can type the item and click Find. If you are using Microsoft Visual Studio and if you 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 want to see all places where that variable is used, simply click the name (and wait two seconds) and all of its occurrences would be highlighted:

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

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 in the Find Symbol Results window:

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

To access a particular section where the variable is used, double-click its entry in the list int the Find 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 Visual Studio. This means that, if you have code you want to use in different sections, you can preserve 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 in Notepad, Microsoft Word, or the Code Editor of Microsoft Visual Studio. You can use code from any document where text can be copied, including a web page. Select that code and copy it to the 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:

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

An alternative is to select the code, whether in the Code Editor or in a text editor. Then drag it and 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 it from 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 name is 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, you can use the Edit -> Replace option of the main menu to find and replace every instance of that name. You can use the same approach in the Code Editor. Unfortunately, this technique works for only one file. If your project has many files and the name is used in those files, it would be cumbersome 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. Consider the following code: Module Exercise Public Sub Main() Dim nbr As Integer nbr = 148 System.Console.WriteLine(nbr) End Sub End Module To change the name of a variable, in the Code Editor, double-click the name of the variable and edit (change) it. The name will then have a small underline:

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

If you position your mouse on it, a tag would appear and you can click the arrow to reveal a short 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 may encounter a variable but you want to find out where it was declared. If you are using Microsoft Visual Studio, to access the place where a variable was declared: Right-click the variable and click Go To Definition...

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

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 that has 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 -> Close Project (Microsoft Visual Basic 2010 Express) 2. When asked whether you want to save, click Discard

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
Previous Copyright 2008-2010 FunctionX Home

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

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 the type 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: "Garage Type: Return 0 End Function End Module Here is an example of running the program: " & TypeOfHouse & vbCrLf & " & TypeOfGarage)

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

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
our program uses the constant 1 in particular meaningful ways. To make it possible to give more meaning to a constant number, when the number can be made part of a series, you can/should create a type of list. An enumeration is a series of constant integers that each has a specific position in the list and can be recognized by a meaningful name. Based on this, instead of just remembering that the constant 1 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 constant 1 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 for you. To manually write the code, on a first line of code, type the Enum keyword followed by a name. 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, rightclick the section where you want to add it and click Insert Snippet... In the menu, double-click Code 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. In that body, add the members of the enumeration, each on its own line. Here is an example: Enum HouseType Unknown SingleFamily TownHouse Condominium End 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 an example: 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:

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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 enumeration would 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. The number 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 a member, assign to the member using the assignment operator "=". Here is an example: Enum HouseType Unknown = 5 SingleFamily TownHouse Condominium End Enum After doing this, the member that follows it would receive a value + 1. In our example, Unknown now would have a value of 5, SingleFamily would have a value of 6 because it follows a member whose value is 1 (thus 5 + 1 = 6). Townhouse would have a value of 7, and Condominium would have a value of 8. You can also assign a value to more than one member of an enumeration. To do this, simply assign the desired value to any member. Here are examples: Enum HouseType Unknown = 5 SingleFamily = 14 TownHouse Condominium = 8 End Enum In this case, Townhouse would have a value of 15 because it follows SingleFamily that has a value of 14.

Enumerations Visibility Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
You can control an enumeration's accessibility outside of its project. This means that you can hide or make it visible outside of its project. To do this, you can precede it with the Private, the Protected, 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 passed as 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 an example: 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 the procedure, you can use the enumeration as you see fit. When calling the procedure, pass an argument 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 Optional keyword to specify that the argument has a default value. When calling the procedure, you can pass or omit passing a value for the argument. Here is an example: Module Exercise Public Enum HouseType Unknown SingleFamily

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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 the enumeration. In the body of the enumeration, do whatever you have to do. Before exiting the function, 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 pt End Function You can call a function that returns an enumeration type by using just its name. Otherwise, you can 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:

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

Home

Copyright 2010 FunctionX, Inc.

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

Strings
Introduction to Strings
Overview
As seen in Lesson 3, a string is one or a combination of characters. To declare a variable for it, you can use either the String or the Object data types. To initialize the variable, put its value 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 syntax is: 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 support this 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:

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

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 combination of characters. From our knowledge of using the computer, we know that, to create a string, we can press the desired characters on the keyboard. An example of a string would be: "Production". To have a repeating 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, that is, to duplicate a character in a string, you can call the StrDup() function. This function is provided in two versions whose syntaxes are: Public Shared Function StrDup( _ ByVal Number As Integer, _ ByVal Character As { Char | String } _ ) As String ' -orPublic 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 the number 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 0 End Function This would produce:

Expression Character Conversion


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

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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. If so, 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-based languages are created in a list or map of character codes. Each character is represented with a small 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 language provides 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 apply some behavior in a program. For example, a combination of Chr(13) and Chr(10) would break a 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 receive an error. The reason you may pass a number higher than 255 is that you may want to get a character beyond those of US English, such as . To support such numbers, the Visual Basic language 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 the memory equivalent to the Short integer data type, which can hold numbers from -32768 to 32767. Normally, you should consider that the character should fit in a Char data type,, which should 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

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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 a string, 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 of characters, 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 the procedure, enter the argument and its name in the parentheses of the procedure. Then, in the body 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 is an 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

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
End Module In the same way, you can apply any of the features we studied for procedures, including passing as many arguments as you want or passing a mixture of characters, strings, and other types 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 the Function keyword and, on the right side of the parentheses, include the Char or String data type 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 it returns 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:

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

In the same way, you can apply any of the features of procedures and functions we studied in Lessons 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 1 e 2 l 3 e 4 v 5 i 6 s 7 i 8 o n

9 10

To find out what character occupies a certain position inside of a string, you can call the GetChar() 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 empty string or Nothing, you would receive an error. The second argument is the position to be consider inside the string. The value must be between 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 numeric equivalent. Here is an example: Public Module Exercise Public Function Main() As Integer Dim Character As Char Dim Number As Integer

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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 a string, which in most cases it can. If it is successful, the function returns a string. Here is an example: 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 be converted 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 = Return 0 End Function End Module This would produce: " & Str(Number))

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

Numeric Hexadecimal Conversion


In Lesson 3, we saw that the Visual Basic language supports hexadecimal number and we saw how to initialize an integer variable with a hexadecimal number. Now, on the other hand, if you have a decimal number but need it in hexadecimal format, you can convert it. To support this operation, 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 hexadecimal equivalent. 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. It returns 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:

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

Case Conversion
If you are presented with a string or an expression whose cases must be the same, you can convert 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. The syntaxes are: Public Shared Function UCase(ByVal Value As Char) As Char Public Shared Function UCase(ByVal Value As String) As String The first version receives a character as argument. If the character is already in uppercase, it would be returned the same. If the character is not a readable character, no conversion would happen and the function would return it. If the character is in lowercase, it would be converted to 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 lowercase in the string would be converted to uppercase. Any letter that is in uppercase would be preserved 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 is overloaded in two versions whose syntaxes are: Public Shared Function LCase(ByVal Value As Char) As Char Public 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, it would be kept "as is". If the character is in lowercase, it would not be converted. If the character 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 the string 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

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
This function produces a string. The first argument of this function is the string whose characters would be converted. The second argument specifies what type of conversion will be performed. This argument is a member of the VbStrConv enumeration. From what we have learned 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. It converts 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 0 End Function VbStrConv.LowerCase: This would have the same effect as the LCase$ function. It converts the first argument's characters to lowercase VbStrConv.ProperCase: The first character of each word of the first argument would be converted 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 0 End Function
This would produce:

The last argument is optional. It allows you to specify that language whose rules would be used to direct the conversion. By default, the compiler refers to the language of the operation system. 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. The primary rule to keep in mind is that a sub-string is part of, and depends on, a string. In other words, 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 from the left side characters of the string, you can use the Left() function. Its syntax is: Public Shared Function Left( ByVal str As String, String ByVal Length As Integer) As

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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 is an 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 a function 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 the number 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, or from somewhere inside an existing string. To assist you with this, the Visual Basic language provides 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:

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

Finding a Sub-String
One of the most regular operations you will perform on a string consists of finding out whether it contains a certain character or a certain contiguous group of characters. To help you with this operation, the Visual Basic language provides the InStr() function. It is overloaded with two versions whose syntaxes are: Public Shared Function InStr(_ ByVal String1 As String, _ ByVal String2 As String, _ Optional ByVal Compare As CompareMethod _ ) As Integer ' -orPublic 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 will be performed. The String2 argument is the character or the sub-string to look for. If String2 is found in String1 (as part of String1), the function return the position of the first character. Here is an 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 for String2. If String1 contains more than one instance of String2, the function returns (only) the position of the first instance. Any other subsequent instance would be ignored. If you want to skip the first instance or want the interpreter to start checking from a position other than the left character, use the second version. In this case, the Start argument allows you to specify the starting 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 start checking 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 the operations you can perform consists of replacing that character or that sub-string with another

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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 is the character or string to look for in the Expression. If that character or string is found, the third argument 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 reversing it. 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 its operation, the function returns a new string made of characters in reverse order. Here is an example: Public Function Main() As Integer Dim StrValue As String Dim StrRev As String StrValue = "Rpublique d'Afrique du Sud" StrRev = StrReverse(strValue) MsgBox(StrValue & vbCrLf & StrRev) Return 0 End 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

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
work with a string that you must first examine. For example, for some reason, a string may contain an empty space to its left or to its right. If you simply start performing a certain operation on it, the operation may fail. One of the first actions you can take on a string would consist of deleting 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. Its syntax 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. Its syntax 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. Its syntax 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 to insert 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 the function 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 argument can have one of the following values: Constant vbBinaryCompare vbTextCompare Here is an example: Private Dim Dim Dim Sub cmdCreate_Click() strValue1 As String strValue2 As String iComparisonValue Value Description 0 1 Perform a binary comparison Perform a textual comparison

strValue1 = "Rpublique 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:

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

Home

Copyright 2008-2010 FunctionX

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in

Incrementing and Decrementing Values


Incrementing a Variable
We are used to counting numbers such as 1, 2, 3, 4, etc. In reality, when counting such numbers, we are simply adding 1 to a number in order to get the next number in the range. The simplest technique of incrementing a value consists of adding 1 to it. After adding 1, the value or the variable is (permanently) modified and the variable would hold the new value. This is illustrated 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 a value in order to get the lesser value. This operation is referred to as decrementing a value. This operation 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

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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 to declare 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 is that each value can hold its own value although the value of the second variable depends on whatever 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

Content downloaded from www.functionx.com

Created by www.ebooktutorials.blogspot.in
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 additional variable. To add a value to a variable and change the value that the variable is holding, you can combine the 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 subtraction operations 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.

Content downloaded from www.functionx.com

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 two categories of procedures you will use in your programs: those that have already been created thus 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 be generated for you. To manually create a procedure, start by typing the Sub keyword followed by a name (like everything else, a procedure must have a name). At the end of the procedure, 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. In addition: If the procedure performs an action that can be represented with a verb, you can use that verb to name it. Here are examples: show, display To make the name of a procedure stand, you should start it in uppercase. Examples are Show, Play, Dispose, Close You should use explicit names that identify the purpose of the procedure. If a procedure would 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 in uppercase. 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

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 variable you 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 String End Sub In the same way, you can declare as many variables as you need inside of a procedure. The actions you perform inside of a procedure depend on what you are trying to accomplish. For example, a procedure can simply be used to create a string. The above procedure can be changed 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, you can use it. Using a procedure is also referred to as calling it. Before calling a procedure, you should 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 an example: Module Exercise Sub Assign() Dim strFullName As String strFullName = "Paul Bertrand Yamaguchi" MsgBox(strFullName)

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 private procedure, a friendly procedure, or a public procedure, using the Private, the Friend, or the Public 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 same application Public: A public procedure can be called from its program and other programs

Practical Learning: Access Modifying a Procedure

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 main difference between a procedure and a function is that, after carrying its assignment, a function gives back a result. We also say that a function "returns a value". To distinguish both, there is a 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 create code for you. To manually create a function, you use the Function keyword followed by a name and parentheses. Unlike a procedure, because a function returns a value, you must specify the type of value the function will produce. To give this information, on the right side of the closing parenthesis, you can type the As keyword, followed by a data type. To indicate where a function stops, 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, rightclick inslde a module 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 Function. 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 and suggestions we reviewed for sub procedures. The As keyword may be required (in the next sections, 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 a word or a group of words, you can create it as String. The other data types are also valid in the 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 function and omit the As DataType expression. The type character is typed on the right side of the function name and before the opening parenthesis. An example would be GetFullname$(). As with the variables, you must use the appropriate type character for the function: Character $ The function must return a String type

% & ! # @ Here is an example: Function GetFullName$() End Function

a Byte, Short, Int16, or In32 an Int64 or a Long a Single type a Double a Long integer

As mentioned already, the section between the Function and the End Function lines is the body of the function. It is used to describe what the function does. As done on a sub procedure, one of the actions you can perform in a function is to declare a (local) variable and use 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 after the 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 which a 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 & ", " & FirstName End Function Alternatively, instead of using the name of the function to indicate the value it returns, you can type 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 & ", " & FirstName End Function You can also use some local variables in the function to perform an assignment and then assign their 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 a procedure 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

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. Like a sub procedure, to call a function, you can simply type its name in the desired section of the program. Here is an example: Sub Main() CallMe End Sub Since the primary purpose of a function is to return a value, to better take advantage of such a value, you can assign the name of a function to a variable in the section where you are calling the 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

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 entry point of a program as we have used it so far. Particularly, Main can be used as a procedure or a function. So far, we have used Main only as a procedure. To use Main as a function, type the Function 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 return value 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 &

"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 a procedure created with the Sub keyword, or a function created with the Function keyword. In the same way, for the rest of our lessons, the word procedure will be used to represent both types. Only when we want to be precise will we use the expression "a procedure" or "a subprocedure" to explicitly mean the type of procedure that does not return a value. When the word "function" is used in our lessons, it explicitly refers to the type of procedure that returns a value.

Accessing a Procedure
If you are using a text editor to write your code, you can use the Edit main menu to do a search on the name of the procedure. If you are using Microsoft Visual Basic, in the top section of the Class View, click the name of the module in which the procedure exists. In the bottom section of the Class View, double-click the name of the procedure. The Code Editor would jump to where the procedure was defined. As an alternative, if you see a section where the procedure gets called in the Code Editor, right-click its name and click Go To Definition. This would 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 text editor like Notepad, you can do a search on its name and replace all instances with a new name. If you are using Microsoft Visual Basic, Find the name of the procedure where it is defined 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

Passing Arguments
Using Global Variables
In the previous lesson, we saw that you could declare a global variable outside of any procedure. When using various procedures in a code file, one of the characteristics of a global variable is that it is automatically accessible to other procedures. Still, a global variable can use 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 the same project. A procedure of another program cannot access that variable

Public: A public global variable can be accessed by any procedure of its project and procedures of other projects

Based on this characteristic of the procedures of a module having access to global variables of the same program, you can declare such variables and initialize or modify them in any procedure of 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 may need an external value in order to carry its assignment. A value that is supplied to a procedure is called an argument. When creating a procedure that will use an external value, declare the argument that represents that value between the parentheses of the procedure. For a procedure, the syntax you use would be: Sub ProcedureName(Argument) End Sub If you are creating a function, the syntax would be: Function ProcedureName(Argument) As DataType Function Sub

The argument must be declared as a normal variable, omitting the Dim keyword. Here is an example 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 the procedure, separate the arguments with a comma. Here is an example of a procedure that takes two 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 see fit as if they were locally declared variables. For example, you can involve them with values inside of the procedure. You can also exclusively use the values of the arguments to perform the assignment.

Calling a Procedure With Argument


To call a procedure that takes an argument, type its name and a space, followed by a value for each argument between parentheses. The value provided for an argument is also called a parameter. If there is more than one argument, separate them with a comma. Here is an example: 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 of the 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 in any 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

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 ByVal keywords; in the next sections, we will learn what that keyword means; for now, keep it but ignore 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 that argument. When this is done, the procedure that is called makes a copy of the value of the argument and makes that copy available to the calling procedure. That way, the argument itself is not accessed. This is referred to as passing an argument by value. This can be reinforced by typing 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 ByVal keyword on the argument, when calling the procedure, you don't need to use the ByVal keyword; just the name of the argument is enough, as done in the examples on arguments so far. 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:

Passing an Argument By Reference


An alternative to passing an argument as done so far is to pass the address of the argument to the procedure. When this is done, the procedure doesn't receive a simple copy of the value of the argument: the argument is accessed by its address. That is, at its memory address. With this technique, any action carried on the argument will be kept. If the value of the argument is modified, the argument would now have the new value, dismissing or losing the original value it had. This technique is referred to as passing an argument by reference. Consider the following program: 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, at the end of the procedure, they lose the value they got in the function. If you want a procedure to 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 when defining the procedure. When the procedure finishes with the argument, the argument would keep whatever modification was made on its value. Now consider the same program as above but 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: ")

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 by value as you want. As you may guess already, this technique is also used to make a procedure return a value, which a regular procedure cannot do. Furthermore, passing arguments by reference allows a procedure to return as many values as possible while a regular function can return 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

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 such an argument is passed with the same value over and over again, you may be tempted to remove the argument altogether. In some cases, although a certain argument is passed with the same value most of the time, you still have situations in which you want the user to decide whether to pass a value or not for the argument, you can declare the value optional. In other words, you can create the argument with a default 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 after discount. The procedure would need the discount rate in order to perform the calculation. Such a 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 would not 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 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 Optional keyword 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:

If a procedure takes more than one argument, you can provide a default argument for each and select 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 desired default 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:

If a procedure takes more than one argument as above, remember that some arguments can be specified as optional. In this case, when calling the procedure, any argument that does not have a default value must be passed with a value. When creating a procedure that takes more than one argument, the argument(s) that has(have) default value(s) must be the last in the procedure. This means that: If a procedure takes two arguments and one argument has a default value, this optional argument must be the second If a procedure is taking three or more arguments and two or more arguments have default values, 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, 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 this procedure, you can pass only one value. In this case, the passed value would be applied on the first argument. If a procedure takes more than two arguments and two or more arguments have a default value, when calling this procedure, you can provide only the value(s) of the argument that is (are) not optional. If you want to provide the value of one of the arguments but that argument is not the first optional, you can leave empty the position(s) of the other argument(s) but remember to type a comma to indicate that the position is that of an argument 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

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 various kinds. 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 same program, you are allowed to use the same name for different procedures of the same program following certain rules. The ability to have various procedures with the same name in the same program is referred to as overloading. The most important rule about procedure overloading is to make sure that each one 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 to the cross section of the beam. Because it depends on the type of section of the beam, its calculation also depends on the type of section of the beam. In this exercise, we will review different formulas used to calculate the moment of inertia. Since this exercise is for demonstration 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:

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 version of the MomentOfInertia() function requires two arguments, we can overload it by 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

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 -> Close Project (Microsoft Visual Basic 2010 Express) 17. When asked whether you want to save, click Discard

Previous

Copyright 2008-2010 FunctionX

Next

Visual Basic Built-In Functions: Conversions


Introduction
You may recall that when studying data types, we saw that each had a corresponding function used to convert a string value or an expression to that type. As a reminder, the general syntax of the conversion functions is: ReturnType = FunctionName(Expression) The Expression could be of any kind. For example, it could be a string or expression that would produce a value such as the result of a calculation. The conversion function would take such a value, string, or expression and attempt to convert it. If the conversion is successful, the function would return a new value that is of the type specified by the ReturnType in our syntax. The conversion functions are as follows: Function Name CBool CByte CDbl CDec CInt CLng CObj CSByte CShort CSng CUInt CULng CUShort Return Type Boolean Byte Double Decimal Integer Long Object SByte Short Single UInt ULong UShort Description Converts an expression into a Boolean value Converts an expression into Byte number Converts an expression into a floating-point number with double precision Converts an expression into a decimal number Converts an expression into an integer (natural) number Converts an expression into a long integer (a large natural) number Converts an expression into an Object type Converts an expression into a signed byte Converts an expression into a short integer Converts an expression into a floating-point number with single precision Converts an expression into an unsigned integer Converts an expression into an unsigned long integer Converts an expression into an unsigned short integer

Type Conversion
Conversion functions allow you to convert a known value to a another type. Besides these functions, 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 expression or 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 what have 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 first argument 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, if the 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 be lower 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 a floating-point number, its resulting value must be convertible to an integer or a floating point number 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 a floating-point number, the second argument is a number-based data type but whose range cannot hold the resulting value of the first argument, the conversion would not be allowed (the conversion will fail):

After the CType() function has performed its conversion, it returns a value that is the same category as the second argument. For example, you can call a CType() function that converts an expression 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 by the 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 an error:

Home

Copyright 2008-2010 FunctionX, Inc.

Static Variables
Introduction
Consider the following program: Public Module Exercise Private Dim Dim Dim Sub Starter(ByVal y As Integer) a As Double = 112.5 b As Double = 175.25 Result As String

a = a / y b = b + 2 Result = "y = "a = "b = "b/a = MsgBox(Result) End Sub " " " " & & & & vbTab vbTab vbTab vbTab & & & & CStr(y) & vbCrLf & _ CStr(a) & vbCrLf & _ CStr(b) & vbCrLf & _ CStr(b / a)

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 also receives the same argument every time. Looking at the result, the argument passed to the procedure and the local variables declared inside of the called procedure keep the same value

every time the procedure is called. That is, when the Starter() procedure exits, the values remain the same. We know that, when a procedure is defined, any variable declared locally belongs to the procedure and its influence cannot expand beyond the body of the procedure. If you want a locally declared variable to keep its changed value when its host procedure is exited, declare such a variable as static.

Declaring a Static Variable


To declare a static variable, type the Static keyword on the left of the Dim keyword. You should always 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 = "a = "b = "b/a = MsgBox(Result) End Sub " " " " & & & & vbTab vbTab vbTab vbTab & & & & CStr(y) & vbCrLf & _ CStr(a) & vbCrLf & _ CStr(b) & vbCrLf & _ CStr(b / a)

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.

Home

Copyright 2008-2010 FunctionX, Inc.

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 an argument is passed with the same value over and over again, you may be tempted to remove the argument altogether. In some cases, although a certain argument is passed with the same value most of the time, you still have situations in which you want the user to decide whether to pass a value or not for the argument, you can declare the value optional. In other words, you can create the argument with a default 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 after discount. The procedure would need the discount rate in order to perform the calculation. Such a 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 would not 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 value would 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

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 and select 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 desired default 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:

If a procedure takes more than one argument as above, remember that some arguments can be specified as optional. In this case, when calling the procedure, any argument that does not have a default value must be passed with a value. When creating a procedure that takes more than one argument, the argument(s) that has(have) default value(s) must be the last in the procedure. This means that: If a procedure takes two arguments and one argument has a default value, this optional argument must be the second If a procedure is taking three or more arguments and two or more arguments have default values, 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, 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 this procedure, you can pass only one value. In this case, the passed value would be applied on the first argument. If a procedure takes more than two arguments and two or more arguments have a default value, when calling this procedure, you can provide only the value(s) of the argument that is (are) not optional. If you want to provide the value of one of the arguments but that argument is not the first optional, you can leave empty the position(s) of the other argument(s) but remember to type a comma to indicate that the position is that of an argument 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 FinalPrice = CalculateNetPrice(225.55, 150.55, , 40) MsgBox("Final Price: " & CStr(FinalPrice)) Return 0 End Function End Module This would produce:

Home

Copyright 2008-2009 FunctionX, Inc.

Overloading a Procedure
Introduction
A program involves a great deal of names that represent variables and procedures of various kinds. 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 same program, you are allowed to use the same name for different procedures of the same program following certain rules.

Overloading a Procedure

The ability to have various procedures with the same name in the same program is referred to as overloading. The most important rule about procedure overloading is to make sure that each one 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 to the cross section of the beam. Because it depends on the type of section of the beam, its calculation also depends on the type of section of the beam. In this exercise, we will review different formulas used to calculate the moment of inertia. Since this exercise is for demonstration purposes, you do not 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

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 version of the MomentOfInertia() function requires two arguments, we can overload it by 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

11. Enter the radius as 6.35

12. Close the DOS window and return to your programming environment

Home

Copyright 2008-2009 FunctionX, Inc.

Visual Basic Built-In Functions: Conversions


Introduction
You may recall that when studying data types, we saw that each had a corresponding function used to convert a string value or an expression to that type. As a reminder, the general syntax of the conversion functions is: ReturnType = FunctionName(Expression) The Expression could be of any kind. For example, it could be a string or expression that would produce a value such as the result of a calculation. The conversion function would take such a value, string, or expression and attempt to convert it. If the conversion is successful, the function would return a new value that is of the type specified by the ReturnType in our syntax. The conversion functions are as follows: Function Name CBool CByte CDbl CDec CInt CLng CObj CSByte CShort CSng CUInt CULng CUShort Return Type Boolean Byte Double Decimal Integer Long Object SByte Short Single UInt ULong UShort Description Converts an expression into a Boolean value Converts an expression into Byte number Converts an expression into a floating-point number with double precision Converts an expression into a decimal number Converts an expression into an integer (natural) number Converts an expression into a long integer (a large natural) number Converts an expression into an Object type Converts an expression into a signed byte Converts an expression into a short integer Converts an expression into a floating-point number with single precision Converts an expression into an unsigned integer Converts an expression into an unsigned long integer Converts an expression into an unsigned short integer

Type Conversion
Conversion functions allow you to convert a known value to a another type. Besides these functions, 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 expression or 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 what have 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 first argument 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, if the 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 be lower 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 a floating-point number, its resulting value must be convertible to an integer or a floating point number 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 a floating-point number, the second argument is a number-based data type but whose range cannot hold the resulting value of the first argument, the conversion would not be allowed (the conversion will fail):

After the CType() function has performed its conversion, it returns a value that is the same category as the second argument. For example, you can call a CType() function that converts an expression 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 by the 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 an error:

Home

Copyright 2008-2010 FunctionX, Inc.

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 with retrieving that part, the Visual Basic language provides the Int() and the Fix() functions. Their syntaxes are: Public Shared Function Int( _ ByVal Number As { Double | Integer | Long | Object | Short | Single | Decimal }) As { Double | Integer | Long | Object | Short | Single Public Shared Function Fix( _ ByVal Number As { Double | Integer | Long | Object | Short | Single | Decimal }) As { Double | Integer | Long | Object | Short | Single

_ | Decimal } _ | Decimal }

Each function must take one argument. The value of the argument must be number-based. This means it can be an integer or a floating-point number. If the value of the argument is integerbased, 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. Here is 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-pointbased 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

End Function End Module This would produce:

Home

Copyright 2008-2010 FunctionX, Inc.

Visual Basic Built-In Functions: Format Number


Introduction
So far, after performing a calculation, we were presenting the result "as is". 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 of passing 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 this function is to pass it a number, a string, or a date/time). The function would then produce that number. Besides the Format() function, the Visual Basic language provides some additional functions we will review below.

Formatting a Number
So far, to display a number, we simply passed it to the MsgBox() function or to another procedure. In some cases, you may want the number to display in a particular format. To control how the number should display, you can pass the second argument of the Format() function. This argument 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 this argument, 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))

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 of digits on the right side of the decimal separator. If you want to display more digits than the number actually has, call the FormatNumber() function and pass a second argument with the desired 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 the decimal separator, specify that number. As a third alternative, you can call the Format() function. In reality, the second argument is used to format the number with many more options. To represent the integral part of a number, you use the # sign. To specify the number of digits to display on the right side of the decimal separator, type a period on the right side of # followed by the number of 0s representing each decimal 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 right side 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 decimal separator, include its character between the # signs. 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:

You can include any other character or symbol you want in the string to be part of the result, but you should include such a character only at the beginning or the end of the string, otherwise the interpreter might give you an unexpected result.

Home

Copyright 2008-2010 FunctionX, Inc.

Introduction to Visual Basic Built-In Functions


Overview of Built-In Procedures
Introduction
A procedure is referred to as "built-in" if it shipped with its programming language. To make your job a little easier, the Visual Basic language is equipped with many procedures that you can use right away in your program. Based on this, before creating your own procedure, first check whether the functionality you are looking for is already implementing in one of the available procedures because those that ship with the Visual Basic language are highly reliable and should be preferred. Before using a built-in procedure, you must of course be familiar with it. This comes either by consulting the documentation or by experience. This means that you must know its name, its argument(s), its return value, and its role. The Visual Basic programming language provides one of the richest libraries you will ever see. In fact, it is the richest of the .NET-based languages, giving you 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 function used to convert a string value or an expression to that type. As a reminder, the general syntax of the conversion functions is: ReturnType = FunctionName(Expression) The Expression could be of any kind. For example, it could be a string or expression that would produce a value such as the result of a calculation. The conversion function would take such a value, string, or expression and attempt to convert it. If the conversion is successful, the function would return a new value that is of the type specified by the ReturnType in our syntax. The conversion functions are as follows: Function Name CBool CByte CDbl CDec CInt CLng CObj CSByte CShort CSng CUInt CULng CUShort Return Type Boolean Byte Double Decimal Integer Long Object SByte Short Single UInt ULong UShort Description Converts an expression into a Boolean value Converts an expression into Byte number Converts an expression into a floating-point number with double precision Converts an expression into a decimal number Converts an expression into an integer (natural) number Converts an expression into a long integer (a large natural) number Converts an expression into an Object type Converts an expression into a signed byte Converts an expression into a short integer Converts an expression into a floating-point number with single precision Converts an expression into an unsigned integer Converts an expression into an unsigned long integer Converts an expression into an unsigned short integer

These functions allow you to convert a known value to a another type. Besides these functions, 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 expression or 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 what have 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 first argument 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, if the 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 be lower 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 a floating-point number, its resulting value must be convertible to an integer or a floating point number 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 a floating-point number, the second argument is a number-based data type but whose range cannot hold the resulting value of the first argument, the conversion would not be allowed (the conversion will fail):

After the CType() function has performed its conversion, it returns a value that is the same category as the second argument. For example, you can call a CType() function that converts an expression 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 by the 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 an error:

Home

Copyright 2008-2010 FunctionX, Inc.

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 of passing 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 this function is to pass it a number, a string, or a date/time). The function would then produce that number. Besides the Format() function, the Visual Basic language provides some additional functions we will review below.

Formatting a Percentage Value


A percentage of a number represents its rate on a scale, usually of 100 (or more). The number is expressed using digits accompanied by the % sign. Besides the Format() function, to support percent values, the Visual Basic language provides a function named FormatPercent. Its syntax is: 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 calling this function, pay attention to the number you provide as argument. If the number represents a percentage value as a fraction of 0 to 1, make sure you provide it as such. An example would be 0.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 by 100. Although it is not impossible to get a percentage value in the hundreds or thousands, you should 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 can call the Format() function and pass the second argument as "Percent", "p", or "P". Here is an example: Public Module Exercise Public Function Main() As Integer Dim DiscountRate As Double DiscountRate = 0.25 MsgBox("Discount Rate: " & Format(DiscountRate, "Percent")) Return 0

End Function End Module

Home

Copyright 2008-2010 FunctionX, Inc.

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 type requires a different amount of space in the computer memory. To know the amount of space that a 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 optionally initialize 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.

Visual Basic Built-In Functions: Random Functions


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 function named 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 would simply 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 the application 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 to get the same result. Depending on how you want to use the number, in some cases, you may want to get a different number every time. To support this, random arithmetic supports what is referred to as a seed. If you do not use a seed, the compiler would keep the same number it generated from the system clock the first time it was asked to produce a random number. Seeding allows 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. Its syntax is: Public Shared Sub Randomize ([ Number ]) This function takes one optional argument. If you can this function without the argument, the compiler would refer to the system clock to generate the new random number. Of course, to get the 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. Instead of 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 some cases you will want the number to be in a higher range, such as between 0 and 100 or between 0 and 100000. All you have to do is to multiply the result to a number of your choice. Here is an example: Public Module Exercise Public Function Main() As Integer Randomize()

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 the number, 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.

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, a Boolean 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 a Boolean 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, a Boolean variable can also deal with numeric values. The False value is equivalent to 0. For example, 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 a procedure. This means that a Boolean variable can be passed to a procedure and/or a function can be made to return a Boolean value. To pass an argument as a Boolean value, in the parentheses of the procedure, type the name of

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 combine Boolean 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 of the 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, you must return a value that evaluates to True or False.

Home

Copyright 2008-2010 FunctionX, Inc.

Logical Operators
Introduction
A comparison is an operation used to get the Boolean result of two values one checked against the 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 of Value2. If Value1 and Value2 hold the same value, the comparison produces a True result. If they are 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 are different. The operator used to perform this comparison is <> and its formula is: Variable1 <> Variable2

If the operands on both sides of the operator are the same, the comparison renders false. If both operands hold different values, then the comparison produces a true result. This also shows that the 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 other operations, the comparison can be made between two variables, as in Variable1 < Variable2. If the value held by Variable1 is lower than that of Variable2, the comparison produces a True.

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:

Equality and Lower Value <=


The previous two operations can be combined to compare two values. This allows you to know if two values are the same or if the first is less than the second. The operator used is <= and its syntax is: Value1 <= Value2 The <= operation performs a comparison as any of the last two. If both Value1 and VBalue2 hold the same value, result is true or positive. If the left operand, in this case Value1, holds a value lower 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 than the 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 a variable while the right operand is a constant. If the value on the left of the > operator is greater than the value on the right side or a constant, the comparison produces a True value. Otherwise, the comparison renders False or null:

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 that of Value2 are the same, the comparison produces a True value. If the value of the left operand is greater than that of the right operand, the comparison still produces True. If the value of the left operand is strictly less than the value of the right operand, the comparison produces a False result:

Home

Copyright 2010 FunctionX, Inc.

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 valid value. This is done by checking a condition. To support this, the Visual Basic language provides a series of words that can be combined to perform this checking. Checking a condition usually produces 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 keywords to check different things. To use them, you must be aware of what each does or cannot do so you would 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: 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 5. To execute the exercise, press Ctrl + F5 6. Enter the Employee name as Helene Mukoko, the hourly salary as 22.35, and the weekly hours as 38

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. This ConditionToCheck can be a simple expression or a combination of expressions. If the ConditionToCheck 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 short enough, 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:

If there are many statements to execute as a truthful result of the condition, you should write the statements on alternate lines. Of course, you can use this technique even if the condition you are examining is short. In this case, one very important rule to keep is to terminate the conditional statement with End If. The formula used is: If ConditionToCheck Then Statement End 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: 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 2. Execute the application 3. Enter the Employee name as Helene Mukoko, the hourly salary as 2W.o5, and the weekly hours as Thirty Eight

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 is initialized 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 is false, 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 that the value of the variable is False. On the other hand, if you want to check whether the variable is True, make sure you include the = True expression. Overall, whenever in doubt, it is safer to always initialize your variable and it is safer to include the = True or = False expression when evaluating the variable: Module Exercise Public Function Main() As Integer Dim IsMarried As Boolean Dim TaxRate As Double TaxRate = 36.45 ' % IsMarried = True

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-Based Functions


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 an example: 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 named Choose. 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 the ConditionToCheck of our If...Then formula. For the Choose() function, this 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 Decimal value). This is the value against which the second argument will be compared. Before calling the function, you must know the value of the first argument. To take care of this, you can first declare a variable and initialize it with the desired value. Here is an example: Module Exercise Public Function Main() As Integer Dim Status As UShort Status = 1

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 each value 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. When the Choose() function is called in an If...Then implementation, if the first argument holds a value of 1, the second argument is validated. When the Choose() function has been called, it returns a value of type Object. You can retrieve that 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 a function 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 when you call the Switch() function in your program. Therefore, you must qualify this function when 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 argument as follows: Switch(ConditionToCheck, Statement) In the ConditionToCheck placeholder, pass a Boolean expression that can be evaluated to True or False. 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 as an enumeration. 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.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 you would like to apply an alternate expression in case the condition is false, you can use the If...Then...Else statement. The formula of this statement is: If ConditionToCheck Then Statement1 Else Statement2 End 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 case Statement2, 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

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 2. Execute the application 3. Enter the Employee name as Helene Mukoko, the hourly salary as 2W.o5, and the weekly hours 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: 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 & "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 6. Execute the application 7. Enter the Employee name as Helene Mukoko, the hourly salary as 22.35, and the weekly hours 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 a function 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 and returns 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 last argument is ignored If the condition is false, the first argument is ignored and the function returns the value of the second argument As mentioned already, you can retrieved the value of the right argument and assign it to the result of the function. The expression we saw early can be written as follows: Module Exercise Public Function Main() As Integer

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 & "======================"

MsgBox(Payroll, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") Return 0 End Function End Module 2. Execute the application 3. Enter the Employee name as Raymond Kouma, the gender as 2, hourly salary as 28.25, and the 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: 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 9. Execute the application 10. Enter the customer name as James Wiley, the start date as 11/07/2008, the end date as 11/10/2008, and the rate applied 49.95

& &

& &

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. The reality is that if there is an alternate value, the function produces a null result. Consider the same program 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:

Notice that the function returns nothing (an empty string). To use this function as an alternative to the If...Then...Else operation, you can pass two values for the second argument. The second argument is actually passed as a list of values. Each value has a specific position as its index. To use 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 an index 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 second argument 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 you want. 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 problem is that if you call it with a value that is not checked by the first argument, the function produces a null value (an empty string). To apply this function to an If...Then...Else scenario, you can call it using the following formula: Switch(Condition1ToCheck, Statement1, Condition2ToCheck, Statement2) In the Condition1ToCheck placeholder, pass a Boolean expression that can be evaluated to True or False. If that condition is true, the second argument would be executed. To provide an alternative to the first condition, pass another condition as Condition2ToCheck. If the Condition2ToCheck is true, then Statement2 would be executed. Once gain, remember that you can get the value returned 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

End Function End Module This would produce:

Home

Copyright 2008-2010 FunctionX

Next

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 offers as many choices as necessary. The formula is: If Condition1 Then Statement1 ElseIf Condition2 Then Statement2 ElseIf Conditionk Then Statementk End If The program will first examine Condition1. If Condition1 is true, the program will execute Statment1 and stop examining conditions. If Condition1 is false, the program will examine Condition2 and act accordingly. Whenever a condition is false, the program will continue examining the conditions until it finds one that is true. Once a true condition has been found and its statement executed, the program will terminate the conditional examination at End If. Here is an example: 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 should provide a "catch all" condition. This is done with a last Else section. The Else section must be the last in the list of conditions and would act if none of the primary conditions is true. The formula to use would be: If Condition1 Then Statement1 ElseIf Condition2 Then Statement2 ElseIf Conditionk Then Statementk Else CatchAllStatement End 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")

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

& &

& &

6. Execute the application 7. Enter the employee number as 54080, the customer name as James Wiley, the start date as 11/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 to perform 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 which would need to be checked for truthfulness or negation. This means that conditional statements can assist a procedure with its assignment. 1. Enter the customer name as Judith Nkolo, the rent start date as 11/05/2008, the rent end date 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 would lead to different results. A function can return only one value (we saw that, by passing arguments by reference, you can make a procedure return more than one value) but you can make it render a result 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 the following 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"

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 a number less than 18 (excluded), the function returns Teen. Here is an example of running the program:

If the user provides a number between 18 (included) and 55, the function returns the Adult. Here is another example of running the program:

What if there is an answer that does not fit those we are expecting? The values that we have returned 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 will not execute any of the returned statements. This means that the execution will reach the End Function line without encountering a return value. This also indicates to the compiler that you wrote a function that is supposed to return a value, but by the end of the method, it didn't return a 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.

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 and the 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, if the execution reaches the end of the function, it would still return something but you would know what 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

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 2. Execute the application 3. Enter the employee number as 54080, the customer name as Sunil Ajat, the start date as 11/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

Using the Immediate If Function


The IIf() function can also be used in place of an If...Then...ElseIf scenario. When the function is called, the Expression is checked. As we saw already, if the expression is true, the function returns the value of the TruePart argument and ignores the last argument. To use this function as an alternative to If...Then...ElseIf statement, if the expression is false, instead of immediately returning 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 the expression 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 you want. In the same, you can call as many IIf functions in the subsequent FalsePart sections as you judge 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 alternative to the If...Then...ElseIf...ElseIf condition, you can pass as many values as you judge necessary for the second argument. The index of the first member of the second argument would be 1. The index of the second member of the second argument would be 2, and so on. When the function is called, it would first get the value of the first argument, then it would check the indexes of the available members of the second argument. The member whose index matches the first argument would 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

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 a constant. Another value can be a string. Yet another value can come from calling a function. Here is an example: Module Exercise Private Function ShowContractors$() Return "=-= List of Contractors "Martin Samson" & vbCrLf "Genevive 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: =-=" & vbCrLf & & & &

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

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 2. Eexecute the application 3. Enter the employee number as 22804, the customer name as George Livingstone, the tank level as 2, the start date as 09/15/2008, the end date as 09/19/2008, and the rate applied 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

argument to this function is passed as a list of values. As seen previously, each value is passed as a combination of two values: ConditionXToCheck, StatementX As the function is accessed, the compiler checks each condition. If a condition X is true, its statement is executed. If a condition Y is false, the compiler skips it. You can provide as many of these 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 the conditions would fit, in which case you can add a last Else statement. The Switch() function also supports this situation if you are using a number, a character, or a string. To provide this last alternative, instead of a ConditionXToCheck expressionk, enter True, and include the necessary statement. 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"

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:", _

"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 2. Eexecute the application 3. Enter the employee number as 86285, the customer name as Genevieve H. Gomoore, the tag number as 924095, the tank level as 3, the start date as 10/22/2008, the end date as 10/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

Conditional Selections
The Select...Case Statement
Introduction
If you have a large number of conditions to examine, the If...Then...Else statement will go through each one of them. The Visual Basic language offers the alternative of jumping to the statement that applies 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 StatementX End 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 be Boolean 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), a decimal number (a Single, a Double, or a Decimal type), a date or time value (a Date type), an enumeration (an Enum type), or else (an Object type). Inside the Select Case and the End Select lines, you provide one or more sections that each contains a Case keyword followed by a value. The value on the right side of Case, ExpresionX, must be the same type as the value of Expression or it can 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 of Expression 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 the value 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:

What Case Else?


The above code supposes that one of the cases will match the value of the Expression factor. This is not always so. If you anticipate that there could be no match between the Expression and one of the Expressions, you can use a Case Else statement at the end of the list. The statement would then look like this: Select Case Expression Case Expression1 Statement1 Case Expression2 Statement2 Case Expressionk Statementk Case Else Statementk End Select In this case, the statement after the Case Else will execute if none of the previous expressions matches 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:

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 &

"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 = Case 2 CarCondition = Case 3 CarCondition = Case Else CarCondition = End Select

"Excellent" "Good" "Drivable" "Unknown"

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 & "------------------------------------------------" "Processed by:" & vbTab & EmployeeName & vbCrLf & "Processed for:" & vbTab & CustomerName & vbCrLf & "------------------------------------------------" "Car Selected:" & vbCrLf & _ vbTab & "Tag #:" & vbTab & TagNumber & vbCrLf & vbTab & "Car:" & vbTab & CarSelected & vbCrLf & vbTab & "Tank:" & vbTab & TankLevel & vbCrLf & "Car Condition:" & vbTab & CarCondition & vbCrLf & "------------------------------------------------" "Start Date:" & vbTab & RentStartDate & vbCrLf & "End Date:" & vbTab & RentEndDate & vbCrLf & "Nbr of Days:" & vbTab & NumberOfDays & vbCrLf & "------------------------------------------------" "Rate Type:" & vbTab & RateType & vbCrLf & "Rate Applied:" & vbTab & RateApplied & vbCrLf & "Order Total:" & vbTab & FormatCurrency(OrderTotal) "===========================" MsgBox(OrderInvoice, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") Return 0 End Function End Module 6. Execute the application 7. Enter the employee number as 92746, the customer name as Antoinette D. Liel, the tag number 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

& vbCrLf & & vbCrLf &

& vbCrLf &

& vbCrLf & & vbCrLf &

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 example you 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 case characters 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

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 of the 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 exactly matches the value sought for. In reality, for this type of scenario, you could validate a range of values. The Visual Basic language provides an alternative. You can check whether the value of the Expression responds to a criterion instead of an exact value. To create it, you use the Is operator with the following formula: Is Operator Value

You start with the Is keyword. It is followed by one of the Boolean operators we saw in the previous lessons: =, <>, <, <=, >, 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 can produce a True or a False result. You can also combine it with the other alternatives we saw previously, 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 &

"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 = Case 2 CarCondition = Case 3 CarCondition = Case Else CarCondition = End Select

"Excellent" "Good" "Drivable" "Unknown"

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 & "------------------------------------------------" "Processed by:" & vbTab & EmployeeName & vbCrLf & "Processed for:" & vbTab & CustomerName & vbCrLf & "------------------------------------------------" "Car Selected:" & vbCrLf & vbTab & "Tag #:" & vbTab & TagNumber & vbCrLf & vbTab & "Car:" & vbTab & CarSelected & vbCrLf & vbTab & "Tank:" & vbTab & TankLevel & vbCrLf & "Car Condition:" & vbTab & CarCondition & vbCrLf & "------------------------------------------------" "Start Date:" & vbTab & RentStartDate & vbCrLf & "End Date:" & vbTab & RentEndDate & vbCrLf & "Nbr of Days:" & vbTab & NumberOfDays & vbCrLf & "------------------------------------------------" "Rate Type:" & vbTab & RateType & vbCrLf & "Rate Applied:" & vbTab & RateApplied & vbCrLf & "Order Total:" & vbTab & FormatCurrency(OrderTotal) "===========================" MsgBox(OrderInvoice, _ MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") Return 0 End Function End Module 2. Execute the application 3. Enter the employee number as 86285, the customer name as Franco Bolero, the tag number as M931429, the car condition as 3, the tank level as 1, the start date as 10/06/2008, the end date as 11/07/2008, and the rate applied 85.50

& vbCrLf & & vbCrLf &

& vbCrLf &

& vbCrLf & & vbCrLf &

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 and take 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 a condition and take an action. The Choose() function is another alternative to a Select...Case statement. 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 our Select 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 Decimal value). This is the central value against which the other values will be compared. Instead of using Case sections, provide the equivalent ExpressionX values as a list of values in place of the second argument. 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 the list uses an index. The first member of the list, which is the second argument of this function, has an index of 1. The second value of the argument, which is the third argument of the function, has an index 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 that 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 Number As UShort, MembershipType As String Number = 1

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 variations of 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 &

"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 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 to the Statement(s) and execute(s) it(them). The compiler keeps doing this check-execution gymnastic. As long as the Condition is true, the Statement(s) section will be executed and the Condition will be tested again. If the Condition is false or once the condition becomes false, the statement 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:

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")

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 another payroll 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), the compiler 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 Condition becomes false, the compiler gets out of this loop and continues with the section under the Loop Until 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

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 = Case 2 CarCondition = Case 3 CarCondition = Case Else CarCondition = End Select

"Excellent" "Good" "Drivable" "Unknown"

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 & 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 5. Execute the application 6. Enter the employee number as 92746, the customer name as James Wiley, the tag number as 297419, the car condition as 1, the tank level as 5, the start date as 11/07/2008, the end 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 as 240759, the car condition as 3, the tank level as 3, the start date as 11/05/2008, the end date 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 tag number as 924095, the car condition as 2, the tank level as 4, the start date as 09/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 tag number as 485M270, the car condition as 2, the tank level as 2, the start date as 11/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 checking a condition that would allow it to repeat. If you want to check a condition first before executing a statement, 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

executes the Statement(s) and checks the Condition again. If the Condition is false, or when the Condition becomes false, the compiler skips the Statement(s) section and continues with the code below 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 the number of times a condition needs to be checked in order to execute a statement. If you know with certainty how many times you want to execute a statement, you can use another form of loops 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 whether the current value (after starting to count) is lower than End. If that's the case, it then executes the 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 this condition 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

End Module

Stepping the Counting Loop


The formula above will increment the counting by 1 at the end of each statement. If you want to control how the incrementing processes, you can set your own, using the Step option. Here is the formula: 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, the Counter 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 be subtracted the set value.

Previous

Copyright 2008-2010 FunctionX, Inc.

Next

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 would display that number. If the user enter a number higher than 5, the program would end but would not display it. In a typical program, after validating a condition, you may want to take action. To do 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 to as nesting a condition. Any condition can be nested in another and multiple conditions can be included 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 user provides such a number, the value of the number is displayed and the user is asked to provide another 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 BCR6 application 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 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 &

"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 5. Execute the application 6. Enter the employee number as 92746, the customer name as James Wiley, the tag number as 297419, the car condition as 1, the tank level as 5, the start date as 10/22/2008, the end 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 in which it is being used. In order to use the Goto statement, insert a name on a particular section of your procedure so you can refer to that name. The name, also called a label, is made of one word and follows the rules we have applied to names (the name can be anything), then followed by a colon ":". The following program uses a For loop to count from 2 to 18, but when it encounters 10, it jumps to 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 and refer to them when you want. Here is an example with various labels: Module Exercise Public Function Main() As Integer Dim Answer As Byte

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: Right: Leaving: Return 0 End Function End Module Here is an example of executing the program with Answer = 1: MsgBox("Wrong: The keyword used to create a constant is Const") GoTo Leaving MsgBox("Right: Constant is not a keyword")

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

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 & "------------------------------------------------" & "Processed by:" & vbTab & EmployeeName & vbCrLf & "Processed for:" & vbTab & CustomerName & vbCrLf & "------------------------------------------------" & "Car Selected:" & vbCrLf & vbTab & "Tag #:" & vbTab & TagNumber & vbCrLf & vbTab & "Car:" & vbTab & CarSelected & vbCrLf & "------------------------------------------------" & "Start Date:" & vbTab & RentStartDate & vbCrLf & "End Date:" & vbTab & RentEndDate & vbCrLf & "Nbr of Days:" & vbTab & NumberOfDays & vbCrLf & "------------------------------------------------" & "Rate Type:" & vbTab & RateType & vbCrLf & "Rate Applied:" & vbTab & FormatCurrency(RateApplied) & "Order Total:" & vbTab & FormatCurrency(OrderTotal) & "===========================" 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")

vbCrLf & vbCrLf &

vbCrLf &

vbCrLf & vbCrLf & vbCrLf &

Loop Until Answer = MsgBoxResult.No Return 0 End Function End Module 2. Execute the application 3. Enter the employee number as 92746, the customer name as James Wiley, the tag number as 297419, the car condition as 1, the tank level as 5, the start date as 10/22/2008, the end 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 number as 297419, the car condition as 1, the tank level as 5, the start date as 11/07/2008, the end 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 the true (or false) value of a condition by making it false (or true). To support this operation, the Visual 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 a simple 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 Boolean variable has been "notted", its logical value has changed. If the logical value was True, it would be changed to False and vice versa. Therefore, you can inverse the logical value of a Boolean variable 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

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 whole condition 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:

In some cases, you may want to exit a conditional statement or a loop before its end. To assist with with this, the Visual Basic language provides the Exit keyword. This keyword works like an operator. It can be applied to a procedure or a For loop. Consider the following ShowNames procedure: 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. Imagine that 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 start displaying the message boxes. After displaying two, the Exit Sub would ask the compiler to stop and get out of the procedure. Because a function is just a type of procedure that is meant to return a value, you can use the Exit keyword to get out of a function before the End Function line. To do this, in the section where 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...Then condition states that if it gets to the point where the number is 4, it should stop. If you use an Exit For statement, the compiler would stop the flow of For and continue with code after the Next keyword.

Exiting a Do Loop

You can also use the Exit operator to get out of a Do loop. To do this, inside of a Do loop where you 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. You may face a customer who wants to purchase a single family house but the house should not cost over $550,001. To implement this scenario, you can first write a program that asks the user to select a type of house and then a conditional statement would check the type of house. 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") Return 0 End Function End Module If the user selects a single family, you can then write code inside the conditional statement of the single 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: "Maximum value afforded: 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?")) " & vbTab & Type & vbCrLf & " & vbTab & FormatCurrency(Value))

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 on another. But you must write one first condition, check it, then nest the other condition. This works fine and there is nothing against it. To provide with with an alternative, you can use what is referred to as a logical conjunction. It consists of writing one If...Then expression that checks two conditions at the same time. To illustrate, once again consider a customer who wants to purchase a 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 an example 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

End Function End Module

To understand how logical conjunction works, from a list of real estate properties, after selecting the house type, if you find a house that is a single family home, you put it in the list of considered properties: Type of House The house is single family House True

If you find a house that is less than or equal to $550,000, you retain it: Price Range $550,000 Value 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 Town House False House Value $625,000 False Result Town House AND $625,000 False

Suppose we find a single family home. The first condition is true for our customer. With the AND Boolean operator, if the first condition is true, then we consider the second criterion. Suppose that the 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 if the first is true, the whole condition is false. This would produce the following table: Type of House Single Family True House Value $750,500 False Result Single Family AND $750,500 False

Suppose we find a townhouse that costs $420,000. Although the second condition is true, the first is false. In Boolean algebra, an AND operation is false if either condition is false: Type of House Town House False House Value $420,000 True Result Town House AND $420,000 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 Single Family True House Value $345,000 True Result Single Family AND $345,000 True

These four tables can be resumed as follows: Condition1 AND Condition2 False False False True

If Condition1 is If Condition2 is False False True True False True False 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 BCR6 application 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 = Case 2 Condition = Case 3 Condition = Case Else Condition = End Select

"Excellent" "Good" "Drivable" "Unknown"

Loop Until (Status > 0) And (Status < 4) Return Condition 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 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 &

"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 5. Execute the application 6. Enter the employee number as 92746, the customer name as James Wiley, the tag number as 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 as 240759, the car condition as 3, the tank level as 3, the start date as 11/05/2008, the end date 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 a single family house that costs up to $450,000 with an indoor garage. This means that the house must 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")

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 compiler evaluates 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 the outcome of the other(s). If the first condition is true, then the second condition is evaluated for its truthfulness: Type of House A Single Family True Property Value B $655,000 False

If the second condition is false, the whole combination is considered false: A True B False A && B False

When evaluating three conditions, if either the first or the second is false, since the whole condition would become false, there is no reason to evaluate the third. If both the first and the second conditions are false, there is also no reason to evaluate the third condition. Only if the first two conditions are true will the third condition be evaluated whether it is true: Type of House A Single Family True Property Value Indoor Garage B $425,650 True C None False

The combination of these conditions in a logical conjunction can be written as A && B && C. If the third condition is false, the whole combination is considered false: A True B True A && B True C False A && B && C False

From our discussion so far, the truth table of the combinations can be illustrated as follows: A False True True B Don't Care False True C Don't Care Don't Care False A && B && C False False False

The whole combination is true only if all three conditions are true. This can be illustrated as follows: A False False True True False B False False False False True C False True False True False A && B && C False False False False False

False True True

True True True

True False True

False False True

Logical Disjunction: OR
Introduction
Our real estate company has single family homes, townhouses, and condominiums. All of the condos have only one level, also referred to as a story. Some of the single family homes have one story, 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 if our 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, we would 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 is true. Even if we were considering another (type of) property, it wouldn't matter. This can be resumed in the following table: Type of House Condominium House True

The other properties would not be considered, especially if they have more than one story: Number of Stories 3 We can show this operation as follows: Condominium One Story Condominium or 1 Story True False True Value False

Creating a Logical Disjunction


To support "either or" conditions in the Visual Basic language, you use the Or operator. Here is an example: 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 each statement in parentheses:

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 no condominium. In this case, we would then consider the other properties: Type of House Single Family House False

If we have a few single family homes, we would look for one that has only one story. Once we find one, our second criterion becomes true: Type of House False One Story Condominium OR 1 Story True True

This can be illustrated in the following run of the above program:

If we find a condo and it is one story, both criteria are true. This can be illustrated in the following table: Type of House False True One Story Condominium OR 1 Story 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 False True True False True False True False Condition1 OR Condition2 True True True False

Here is another example of running the program:

Practical Learning: Using Logical Disjunctions


1. Start Microsoft Visual Basic and create a Console Application named BCR7 (or open the BCR6 application 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 = Case 2 Condition = Case 3 Condition = Case Else Condition = End Select

"Excellent" "Good" "Drivable" "Unknown"

If (Status < 1) Or (Status > 3) Then

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

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 5. Execute the application 6. Enter the employee number as 92746, the customer name as James Wiley, the tag number as 297419, the car condition as 1, the tank level as 5, the start date as 11/07/2008, the end 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 as 240759, the car condition as 3, the tank level as 3, the start date as 11/05/2008, the end date 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 tag number as 924095, the car condition as 2, the tank level as 4, the start date as 09/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 tag number as 485M270, the car condition as 2, the tank level as 2, the start date as 11/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 them and must consider a combination of more than two conditions. You would apply the same logical approach we reviewed for the logical conjunction, except that, in a group of logical disjunctions, if one of them is true, the whole statement becomes true.

Previous

Copyright 2008-2010 FunctionX, Inc.

Home

Introduction to Classes
Programmer-Defined Types
Introduction
In the Visual Basic language, you can combine a group of variables into an entity. These variables become considered as one. You can then declare one or more elaborate variables from this enhanced 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:

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 the Class keyword followed by a name. The name of a class follows the rules we have applied so far for variable and function names. 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 that composes the class is represented as a complete variable declared with a name and a data type. By adding a Length and a Height variables, our class would become: Class Rectangle Dim Length As Double Dim Height As Double End Class The items that compose a class are called members of the class. When creating the members of a class, you can omit the Dim keyword: Class Rectangle Length As Double Height As Double End 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-click the 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 the suggested 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 customer has given you a preliminary catalog as follows:

Stock #: 437876 Crinkled Georgette Dress Unit: $42.95

Stock #: 790475 New Wool Comfort Pants $38.75

Stock #: 740797 Pencil Skirt $25.75

Stock: 608432 Silver 1/10-ct. T.W. Diamond Heart-Link Bracelet $95.85

Stock #: 759470 Multistriped Organic Cotton Dress Shirt $35.50

Stock #: 487046 Modest Dress Heels $35.50

Each item in this catalog is represented by its Stock number, its name or description, and its price. 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 Double End 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 this control. You define what member variables can be accessed from outside the class and members that must not be accessed outside. This means that when creating a class, you specify what members are friendly, public, or private.

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 same application. Classes and modules outside of its application cannot access such a member. To create such a member variable, precede it with the Friend keyword. Here is an example: Class Rectangle Friend Height As Double End 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 Double End 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 to be 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 Double End 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 can make 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 is referred to as private if it can be accessed only within the module where it is created, that is, only by members of the same 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 application to 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 Double End Class

A Public Class

Although you may think of working only in Visual Basic, in some cases, you may create a class and want to share it with code written in another language such as C++/CLI or C#, to make this possible, you can give "public" access to your class. If you want your class to be accessible to code written in other languages, precede the Class keyword with Public when creating it. Here is an example: Public Class Circle Friend Radius As Double End 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 the class. The compiler would do this. Later on, to access any member variable of the class, you must get a reference to the area of memory where the members of the class are located. To do this, when declaring the variable for the class, to reserve the necessary area of memory, use the New operator followed by the name of the class and assign this expression 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 declaring the variable by inserting the New operator between the As keyword and the name of the class. This can be done as follows: 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 for it, 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

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 called an 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 the members 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 the member 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, the list of members would appear:

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 want to 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. By default, each member variable must be initialized on its own line. Here are examples: Module Exercise Private Class Rectangle Public Length As Double Friend Heigh

The Methods of a Class


Methods Fundamentals
Introduction
The variables of a program cannot perform assignments. In the same way, the member variables of 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 a procedure 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 customer has given you a preliminary catalog as follows:

Stock #: 437876 Crinkled Georgette Dress Unit: $42.95

Stock #: 790475 New Wool Comfort Pants $38.75

Stock #: 740797 Pencil Skirt $25.75

Stock: 608432 Silver 1/10-ct. T.W. Diamond Heart-Link Bracelet $95.85

Stock #: 759470 Multistriped Organic Cotton Dress Shirt $35.50

Stock #: 487046 Modest Dress Heels $35.50

Each item in this catalog is represented by its Stock number, its name or description, and its price. 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

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 is selected. 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 Double End 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. For example, 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

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 Sub End 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 the member 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

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 an example: Class Rectangle Length As Double Height As Double Sub Show() End Sub End Class When you have created a member variable in a class, it is available to all methods of the same class. This means that, to use it from a method of the same class, you do not have to declare a variable 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() method without 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 not return a value. Like a normal procedure, a method can be made to return a value, in which case it would be a function. To create a method as a function, use the same techniques we have used so far to create a function. Here is an example:

Friend Class Rectangle Public Length As Double Public Height As Double Function Assign() As Double End Function End Class After declaring a procedure, in its body, you can implement the expected behavior. As seen for a sub procedure, when a method has been created, it has access to all of the other members of the same class. This means that you don't have to re-declare a member of a class to access it in a method. 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 a member variable. A normal sub procedure can take care of this. Instead, you would create a method if you need to perform a calculation and get a value from it instead of storing that value in one of the member variables. Here is an example: Friend Class Rectangle Public Length As Double Public Height As Double

Function Assign() As Double End Function Function Perimeter() As Double End Function End Class Therefore, in the body of the function, you can access a member variable, you can call another method of the same class, or you can use an external value as you see fit. When the function exits, 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 Function End Module This would produce:

Like a sub procedure that is created as a method, a member function of a class can be made private, 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")

UnitPrice = CDbl(InputBox("=#= vbCrLf & _ vbCrLf & _

Department Store =#=" &

" --- Item Registration ---" & 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

1.

Methods and Arguments


Like regular procedures we have used so far, methods can have arguments. The rules are the same as we have applied them so far. When you create a method, it has direct access to all regular members of its class. This means that you don't have to create an argument for a member variable of the same class. You would need an argument only if an external value would be passed to 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 have different 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 Sub End 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 Function End 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 of declaring a variable of the class, the other had to do with Shared members. We know already that the members of a class are made available to all other members of the same class without being declared 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 Sub End Class When the Area variable is used in the Display() method, there are two variables available and named Area. It makes it confusing to know what particular variable is being accessed. You can use a 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. Here is 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

' 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 is used 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 Sub End Class

Home

Copyright 2008-2010 FunctionX, Inc.

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 Function End Module This would produce:

Notice that this program indicates that the Side member variable of the Square class was initialized with 0. This means that, like the regular variables, the member variables of a class are initialized by the compiler with default values that depend on the type of the variable. For example, a numeric member variable is initialized with 0 while a string-based variable is initialized with an empty string. After adding a member variable to a class, instead of relying on the default value assigned by the compiler, 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 customer has given you a preliminary catalog as follows:

Stock #: 437876 Crinkled Georgette Dress Unit: $42.95

Stock #: 790475 New Wool Comfort Pants $38.75

Stock #: 740797 Pencil Skirt $25.75

Stock: 608432 Silver 1/10-ct. T.W. Diamond Heart-Link Bracelet $95.85

Stock #: 759470 Multistriped Organic Cotton Dress Shirt $35.50

Stock #: 487046 Modest Dress Heels $35.50

Each item in this catalog is represented by its Stock number, its name or description, and its price. 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 Miscellaneous End 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

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 Sub End 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 Function End Module This would produce:

Notice that, this time, the default value assigned to the member variable applies. Instead of initializing a member variable when declaring it, you can create a method that would be used to do this. Here is an example: Public Class Square Private side As Double Public Sub SetSide() side = 48.25 End Sub End Class

Such a method can also be used to initialize more than one value. When you create a method used to initialize one or more member variables of a class, if you want the initialization to apply, you must 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 that method 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 Function End Module Here an example of running the program:

Notice that, although the Square.Side member variable is private, you cab call the SetSide() public method to initialize it before displaying the characteristics of a square.

Practical Learning: Initializing the Member Variables of a Class

1. Change the StoreItem class as follows:

Public Enum ItemCategory Women Men Girls Boys Babies Jewelry Beauty Bedroom Miscellaneous End Enum Public Class StoreItem Friend ItemNumber As Long Friend Category As ItemCategory Friend ItemName As String Friend UnitPrice As Double Public Sub Initialize(ByVal ByVal ByVal ByVal ItemNumber = Number Category = Type ItemName = Name UnitPrice = Price End Sub Number As Long, _ Type As ItemCategory, _ Name As String, _ Price As Double)

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 Sub End 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

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 members of 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 particular constructor is called the default constructor. You have the option of creating it or not. Although a constructor 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 Sub End Class Like every method, a constructor is equipped with a body. In this body, you can access any of the member 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 Function End Module When executed, it would produce:

This shows that, when a class has been instantiated, its constructor is the first method to be called. For this reason, you can use a constructor to initialize a class, that is, to assign default values to its member variables. Based on this, instead of initializing the member variable(s) of a class when initializing it or them, or instead of creating a special method used to initialize the member variable(s) of a class, you can use a constructor to do this. The advantage of a constructor is that it doesn't need to be called: it is automatically available whenever the class is instantiated.

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:

Public Enum ItemCategory Women Men Girls Boys Babies Jewelry Beauty Bedroom Miscellaneous End 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 Sub End 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

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 that you create; you just havce the option of explicitly creating one or not. The default constructor as we saw it doesn't take arguments: this is not a rule, it is simply assumed. Instead of a default constructor, 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 Sub End Class With this type of constructor, when you declare an instance of the class, you can use this new constructor 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 Function End 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 you declare an instance of the class and use the default constructor to initialize it, you would receive an error when you compile the program. Based on this, the following program will produce an error: 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 Function End Module If you still want to use the default constructor in a class after creating a constructor that takes at least 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 Miscellaneous End 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 ByVal ByVal ByVal ItemNumber = Number Category = Type ItemName = Name UnitPrice = Price End Sub As Long, _ Type As ItemCategory, _ Name As String, _ Price As Double)

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 Sub End 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 of a class when the class is instantiated. A constructor that plays this role of initializing an instance of a class is also called an instance constructor. Most of the time, you don't need to create a constructor, since one is automatically provided to any class you create. Sometimes though, as we have seen in some classes, you need to create your own constructor as you judge it necessary and sometimes, a single constructor may not be sufficient. For example, when creating a class, you may 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 class and give it more than one constructor. The same rules used on overloading regular methods also apply to constructors: the different constructors must have different number of arguments or different types of arguments.

Practical Learning: Overloading a Constructor

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 Miscellaneous End 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),

_ _

MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _ "Department Store") End If End Sub End 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:

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 to provide you some memory space in the heap memory. The compiler is said to "allocate" memory for 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 available to 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 the programmer 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 of memory would be available and used while the program is running and as long as the compiler judges this necessary. While the program is running, the instance of the class uses or consumes the computer's resources as necessary. When the object is not needed anymore, for example when the program terminates, the object must be destroyed, the memory it was using must be emptied to be made available to other programs on the computer, and the resources that the object was using should (must) be freed to be restored to the computer so they can be used by other programs. To make this possible, the Object class is equipped with a method called Finalize that 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 compiler judged that the instance of the class was not used anymore. If you don't want this method to be called, 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

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 can make a member variable of class to be constant. To do this, follow the same formula we used previously 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 Function End 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 you wanted its value to be constant. This can also be applied to a member of a class. To do this, follow the same formula we saw for those variables, except that the variable should be made a member of the class. Unlike a constant variable that you must initialize when creating it, you can declare a ReadOnly 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 a constant. Here is an example: Public Class Circle Public Radius As Double Public Const Twice As Integer = 2 Public ReadOnly PI As Double = 3.14159 End Class Alternatively, you can initialize the variable in the(a) constructor of its class. This would be done as follows: 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

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 Function End Module This would produce:

If the value held by a read-only member variable is gotten from an expression, then the value should be initialized in the(a) construction with the desired expression. If you don't rightly initialize it, 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 Function End 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't need 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 member variable can hold different values depending on the particular constructor that is accessed at a particular time but the value of a constant variable cannot change: it is initialized once, in the class (or in a method) and it keeps that value throughout the class (or method).

A Class as a Field

Just like any of the variables we have used so far, you can make a class or a structure a member variable of another class. To use a class in your own class, of course you must have that class. You can use one of the classes already available in C# or you can first create your own class. Here is an example of a class: Public Class Point Friend x As Short Friend y As Short End Class A field is a member variable created from another class instead of a primitive type. To use one class as a member variable of another class, simply declare its variable as you would proceed with any of the member variables we have declared so far. Here is an example: Public Class Point Friend x As Short Friend y As Short End Class Public Class CoordinateSystem Private Start As Point End 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 to use it. After declaring the member variable, you must make sure you have allocated memory for it. 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, position the 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

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 Sub End 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 do this, you can first declare the method and specify the class as the return type. Here is an example: 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 End Function End Class After implementing the method, you must return a value that is conform to the class, otherwise you would receive an error when compiling the application. You can proceed by declaring a variable of the class in the body of the method, initializing the variable, and then returning it. Here is an example: 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 End 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

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 Function End Module

Passing a Class as Argument


Once a class has been created, it can be used like any other variable. For example, its variable can be passed as argument to a procedure or to a method of another class. When a class is passed as argument: Its public members are available to procedures and classes of its project and procedures and classes 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 Function End Module Here is an example of running the program:

As done for the arguments of primitive types, you can pass more than one class as argument to a method. Because classes are always used as references, when passing a class as argument, it is implied to be passed by reference. To reinforce this, you can type the ByRef keyword to the left of the argument. 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 Function End 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 & _

"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 # Category Make Model Unit Price Discount 917305 e Sennheiser HD280 Pro Closed-Back Headphones 99.95 20

Quantity

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 have programmed in C++, an example of this implementation is the copy constructor; although you can legitimately 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 .NET Framework). To do this, you primarily pass the argument as if it were any class. Here is an example: Public Class Point Friend x As Integer Friend y As Integer Public Sub Equivalent(ByVal Same As Point) End Sub End Class Then, in the body of the method, do whatever you want. You can, or you may not, use the argument. Still, if you decide to use the argument, know that all of the other members of the class are available through the argument. Probably the simplest way to use the argument is the assign 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 Sub End Class When calling the method, make sure you pass an instance of the class to it. You can first create and 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)

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 Function End Module This would produce:

Instead of first declaring a variable of the class and initializing it, you can create an instance of the class in the parentheses of the calling method. To do this, you may need a constructor that can specify the values of the fields of the class so the argument can be rightfully initialized. 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 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 Function End Module This would produce:

Instead of a formal method, you can use a constructor of the class to pass an instance of the same class. Then, in the constructor, use the argument as you see fit, knowing that all the members 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 Sub End 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 but modifies that instance. For example, for our Point class, we may want to create a new point that is distanced 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 Function End Module This would produce:

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 side of the method, enter the name of the class. Here is an example: Public Class Point Public Function MethodName() As Point End Function End Class There are various ways you can deal with the method. If you want to return a new value of the class, 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 Function End Module This would produce:

Alternatively, you can declare an instance of the class, use the current values of the class combined 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 the class from where you are calling the method. The second type of implementation consists of modifying the instance of the class that is calling the method. For example, you can add values to its fields or you can perform any other operation you want on the members of the calling instance. 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 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 Function End Module This would produce:

As we have learned now, you can create a method that takes an argument that is the same type as its parent class. In the method, you can access any member of the class, including calling the other methods of the class.

Home

Copyright 2008-2010 FunctionX

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 as you see fit. Just as you can declare one instance of a class, in the same way, you can declare as many instances as you judge it necessary. After declaring various variables of the same class and initializing them, each variable has and keeps 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 variable of the class. The Visual Basic language provides an alternative. You can declare a member variable so that you can access it from anywhere in your code without primarily declaring a variable of the class. 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. After the shared member variable has been declared, you can use it like any other member variable of

that class, except that you don't need to declare an instance of that class when you want to access 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 Function End Module This would produce:

Based on this, when creating a class, you will decide whether you want a particular member variable to be shared or not. You can have only one, two, more, or all member variables shared in a 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 methods are more used than shared member variables because a shared method allows performing an action on a class without declaring an instance of that class. To create a shared method, type the Shared keyword on the left of the Sub or the Function keyword. Here is an example:

Here is an example: Friend Class Rectangle Shared Function CalculatePerimeter#() Return (Length + Height) * 2 End Function End 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 Function End Class Like a shared member variable, once a method has been created as shared, it can be accessed directly from anywhere. Remember that you would need to type the name of the class before accessing the method. The name of the class allows you to "qualify" the method. Here is an example: 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.

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 can make a member variable of class to be constant. To do this, follow the same formula we used previously 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 Function End 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 you wanted its value to be constant. This can also be applied to a member of a class. To do this, follow the same formula we saw for those variables, except that the variable should be made a member of the class. Unlike a constant variable that you must initialize when creating it, you can declare a ReadOnly 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 a constant. Here is an example: Public Class Circle Public Radius As Double Public Const Twice As Integer = 2 Public ReadOnly PI As Double = 3.14159 End Class Alternatively, you can initialize the variable in the(a) constructor of its class. This would be done as follows: 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

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 Function End Module This would produce:

If the value held by a read-only member variable is gotten from an expression, then the value should be initialized in the(a) construction with the desired expression. If you don't rightly initialize it, 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 Function End 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't need 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 member variable can hold different values depending on the particular constructor that is accessed at a particular time but the value of a constant variable cannot change: it is initialized once, in the class (or in a method) and it keeps that value throughout the class (or method).

A Class as a Field

Just like any of the variables we have used so far, you can make a class or a structure a member variable of another class. To use a class in your own class, of course you must have that class. You can use one of the classes already available in C# or you can first create your own class. Here is an example of a class: Public Class Point Friend x As Short Friend y As Short End Class A field is a member variable created from another class instead of a primitive type. To use one class as a member variable of another class, simply declare its variable as you would proceed with any of the member variables we have declared so far. Here is an example: Public Class Point Friend x As Short Friend y As Short End Class Public Class CoordinateSystem Private Start As Point End 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 to use it. After declaring the member variable, you must make sure you have allocated memory for it. 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, position the 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

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 Sub End 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 do this, you can first declare the method and specify the class as the return type. Here is an example: 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 End Function End Class After implementing the method, you must return a value that is conform to the class, otherwise you would receive an error when compiling the application. You can proceed by declaring a variable of the class in the body of the method, initializing the variable, and then returning it. Here is an example: 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 End 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

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 Function End Module

Passing a Class as Argument


Once a class has been created, it can be used like any other variable. For example, its variable can be passed as argument to a procedure or to a method of another class. When a class is passed as argument: Its public members are available to procedures and classes of its project and procedures and classes 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 Function End Module Here is an example of running the program:

As done for the arguments of primitive types, you can pass more than one class as argument to a method. Because classes are always used as references, when passing a class as argument, it is implied to be passed by reference. To reinforce this, you can type the ByRef keyword to the left of the argument. 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 Function End 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 & _

"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 # Category Make Model Unit Price Discount 917305 e Sennheiser HD280 Pro Closed-Back Headphones 99.95 20

Quantity

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 have programmed in C++, an example of this implementation is the copy constructor; although you can legitimately 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 .NET Framework). To do this, you primarily pass the argument as if it were any class. Here is an example: Public Class Point Friend x As Integer Friend y As Integer Public Sub Equivalent(ByVal Same As Point) End Sub End Class Then, in the body of the method, do whatever you want. You can, or you may not, use the argument. Still, if you decide to use the argument, know that all of the other members of the class are available through the argument. Probably the simplest way to use the argument is the assign 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 Sub End Class When calling the method, make sure you pass an instance of the class to it. You can first create and 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)

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 Function End Module This would produce:

Instead of first declaring a variable of the class and initializing it, you can create an instance of the class in the parentheses of the calling method. To do this, you may need a constructor that can specify the values of the fields of the class so the argument can be rightfully initialized. 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 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 Function End Module This would produce:

Instead of a formal method, you can use a constructor of the class to pass an instance of the same class. Then, in the constructor, use the argument as you see fit, knowing that all the members 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 Sub End 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 but modifies that instance. For example, for our Point class, we may want to create a new point that is distanced 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 Function End Module This would produce:

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 side of the method, enter the name of the class. Here is an example: Public Class Point Public Function MethodName() As Point End Function End Class There are various ways you can deal with the method. If you want to return a new value of the class, 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 Function End Module This would produce:

Alternatively, you can declare an instance of the class, use the current values of the class combined 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 the class from where you are calling the method. The second type of implementation consists of modifying the instance of the class that is calling the method. For example, you can add values to its fields or you can perform any other operation you want on the members of the calling instance. 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 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 Function End Module This would produce:

As we have learned now, you can create a method that takes an argument that is the same type as its parent class. In the method, you can access any member of the class, including calling the other methods of the class.

Home

Copyright 2008-2010 FunctionX

Nesting a Class
Description
A class can be created inside of another class. A class created inside of another is referred to as nested. To nest a class, simply create it as you would any other. Here is an example of a class called Inside that is nested in a class called Outside: Public Class Outside Public Class Inside End Class End Class In the same way, you can nest as many classes as you wish in another class and you can nest as many classes inside of other nested classes if you judge it necessary. Just as you would manage any other class so can you exercise control on a nested class. For example, you can declare all necessary fields, properties, or methods in the nested class or in the nesting class. When you create one class inside of another, there is no special programmatic relationship between both classes: just because a class is nested does not mean that the nested class has immediate access to the members of the nesting class. They are two different classes and they can be used separately as you judge it necessary. The name of a nested class outside of the nesting class, use it. For example, if you outside of Outside, you must is not "visible" outside of the nesting class. To access a nested class you must qualify the name of the nested class anywhere you want to want to declare an Inside variable somewhere in the program but 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 Function End 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 static members. In other words, if you want, you can declare static all members of the nested class that you 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

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 Function End Module In the same way, if you want to access the nesting class in the nested class, you can go through the static members of the nesting class. To do this, you can declare static all members of the nesting 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 Function End 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 you want to access members of a nesting class in the nested class, you can first declare a variable of the nesting class in the nested class. Here is an example:

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 Function End Module This would produce:

Previous

Copyright 2008-2010 FunctionX

Next

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 Double End 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 of the Circle class, it is a good idea not to directly expose them to other parts of the program so that those other parts would not be able to easily change the values of the members and retrieve their values anyhow. This technique makes sure that a member variable is not accessed outside the class (or structure) so that the clients of the class (or structure) cannot directly influence the value of 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) or procedures to access or get the value of such a member variable, you should then provide a means 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 of an employee, a property can be the "door" that other procedures or classes that need the salary must present their requests to. As such, these external procedures and classes cannot just change the salary or retrieve it as they wish. A property can be used to validate their request, to reject or to 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 the purpose of creating a property)) member variable as we did for the rad member variable of the above Circle class. Obviously, as we learned in Lesson 21, this private member variable cannot be accessed by a procedure or class outside of its class. Therefore, to let outside classes access this variable, you would/can create a property. To create a property, you use the Property keyword. With regards to their 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:

Public Class DepartmentStore Private pItemNo As String Private pCat As String Private pName As String Private pSize As String Private pPrice As Double End 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 member variable it represents. To create a read-only property, use a formula as follows (this formula takes into consideration only the keywords we have learned so far; there are other options that we choose to ignore at this time): Public | Private | Protected ] [ ReadOnly ] [ Overloads | Overrides ] _ [ Overridable ] | Shadows | Shared ] Property PropName As PropType Get End Get End Property The optional Public, Private, or Protected keywords allow you to specify the level of access of the property. As introduced in the Lesson 11, the Public keyword would indicate that the property can be accessed outside of its class. The Private keyword would show that the property is available only to members of its class. The Protected keyword would indicate that the property can be 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 of its class. The ReadOnly keyword is used to indicate that the property's value can be accessed but it cannot be 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 name essentially follows the rules of Visual Basic object names. The Get keyword, the End Get and the End 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 Property End Class Notice that we omitted the As keyword and the data type of the property. If you don't specify the data type, the property is treated as Object. Otherwise, you can specify the necessary data type of the property. Here is an example: Public Class Circle ' This is a new property Public ReadOnly Property Radius() As Double Get End Get End Property End Class Between the Get and the End Get lines, you can implement the behavior that would be used to make the member variable's value available outside. The simplest way consists of just returning the corresponding member variable. To do this, type the Return keyword, followed by the hidden member 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 the property but they cannot change it. Therefore, if you create a read-only property, you should

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 constructor used 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, for example 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 usually unrealistic for the side of a square. In this case and others, while still protecting the member variable as private, you can use the read property to reset the value of the member variable or even to reject it. To provide this functionality, you can create a conditional statement in the property 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

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 Property End 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

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 #: 53564 Category: Men Description: Khaki Pants Sahara Item Size: 34 Unit Price: $24.95 Quantity: 4 Total 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 member variable. This meant that we had to always make sure that we knew the value of the member variable when we declared an instance of the class. We implemented the Radius property as readonly and the clients of the Square class could only read the value of the member variable. In some cases, you may not want those external procedures or classes to read the value but only to be able to change it. To provide this functionality, you can create a property that is referred to as write-only. A property is called write-only if the clients of the class can change the value of that property but cannot read. The formula to create a write-only property is (once again, this formula mentions only 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 Set End Property The WriteOnly keyword is used to indicate that the property's value can be changed by the clients of the class but they cannot change it. If you are creating a write-only property, you must include the WriteOnly keyword. To allow clients of a class to be able to change the value of the property, the Set statement takes an 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 that would be provided by the outside world. To do this, you can assign the value of the Set argument to the corresponding member variable that the property represents. 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) rad = Value End Set End Property End Class As you see, clients of a class can change the corresponding member variable of a member variable through 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-only property restricts the ability to read the value it holds. In some rare cases, you can keep these two functionalities separate. In most cases, when creating a property, you would want its role to serve as a complete "door" through which the clients of a class can read or change the value of its hidden 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 to either change its value or to read that value when necessary. To create a read-write property, you must 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 Set End Property Notice that, because this is a read-write property, you omit the ReadOnly and the WriteOnly keywords. When implementing the property, provide the necessary functionality in the Get and Set statements 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

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.25 Diameter: 128.5 Circumference: 403.69303 Area: 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 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 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

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 Property End 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 #: 53564 Category: Men Description: Khaki Pants Sahara Item Size: 34 Unit Price: $24.95 Quantity: 4 Total Price: $99.80 =#=#= Customer Invoice =#=#= Item #: 74797 Category: Womn Description: Suit Gallantry Item Size: 10-1/4 Unit Price: $225.75 Quantity: 2 Total Price: $99.80

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 builtin 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, you can 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

Operator Overloading
Fundamentals of Overloading an Operator
Introduction
In elementary school, we learned how to perform arithmetic operations such as adding 2 to 5 to get 7. We also learned somehow how to add letters to create a word, how to add words to create a sentence, and how to add symbols to create abbreviations. In programming, we learn how to create classes that are made of more than one value. When necessary, we may want to add the values of those classes to get new values. Unfortunately, those classes are not equipped to perform arithmetic operations or comparisons on their objects. Fortunately, if you judge it necessary, you can write code that makes it possible. We know many of the operators available in the Visual Basic language. We also reviewed some of the ways they can be used. We saw that there are rules that must be followed when using any of those operators. Operator overloading consists of customizing the behavior of a Visual Basic operator to be able to apply it on the values of a class. This means that you must create a special behavior in your class for a particular operator you want to use. A class whose operators you want to overload primarily starts like any class. You can add any members you judge necessary to it. Make sure you provide appropriate and realistic constructors so the class can be initialized appropriately. The other important detail you should take care of is how the value of the class will be accessed outside. Probably the easiest way to do this consists of overriding 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 Function End 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 Function End Class

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 Function End 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 ]

Return returnvalue [ statements ] End Operator You can start with the Public access modifier, followed by the Shared keyword. You can use additional keywords and/or mechanisms to control access to the method. You must then use the Operator keyword. This is followed by the actual operator you want to customize. There are rules you must, and suggestions you should, follow: Not all operators need to be customized for all classes. For example, while it would be feasible to add two books to get a new book that includes all the pages on both books and their combined authors, it may not be realistic to multiply two books (to get what?). Therefore, you should select the right operator based on your needs While some operators are always available to be overloaded, some operators have restrictive rules. 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 the parentheses, you will add one or more arguments, depending on the operator. After the closing parenthesis, 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 a value that represents its class. To end the method, you must use the End Operator expression. In the body of the method, you can implement the behavior and make sure you return a value. After defining the method, you can call 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 unary operators 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 body of the method, perform the desired operation. Here is an example of overloading a unary operator: 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 Function End 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:

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 Visual Basic 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 argument can 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 Function End 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 argument must be of the same type as the first, which is the class you are using.

Application: Overloading Binary Operators

1. Access the Rational.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 Function End Class 2. Access the Algebra.vb file and change it as follows: Module Algebra Public Function Main() As Integer Dim a, b, c, d As Long Dim FirstFraction As Rational = Nothing Dim SecondFraction As Rational = Nothing

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: FirstFraction)) SecondFraction = New Rational(c, d) MsgBox(String.Format("Second Fraction: SecondFraction)) Dim Dim Dim Dim Addition As Rational Subtraction As Rational Multiplication As Rational Division As Rational {0}/{1} => {2}", a, b, {0}/{1} => {2}", c, d,

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 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

Binary Bitwise Operators


Besides the traditional arithmetic operations, Visual Basic support the ability to add or shift bits in the computer memory. These operators are the bitwise conjunction operator & and its assignment operator &=, the bitwise disjunction operator | and its assignment operator |=, the bitwise exclusion operator ^ and its assignment operator ^=, the left-shift operator << and its assigment operator <<=, the right-shift operator >> and its assignment operator >>=. When necessary, overload only the primary operator (&, |, ^, <<, >>) and its equivalent assignment operator will be automatically provided by the compiler. To overloaded a binary operator, pass two arguments to the parentheses of the method. For the two bitwise shift operators, << and >>, the first argument must be the class in which you are working and the second argument must by a constant integer (type int). Here is an example that overloads 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

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 Function End 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 be an 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 be a 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

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 Function End 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 the other. The values must be of the same type. Comparison operators go in pair. That is, if you want to compare two values for equality, you must also be able to know when they are different. For this 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 it possible to find out whether one object is equal to another. And since all classes in a Visual Basic application derive from Object, if you decide to overload a couple of comparison operators, you should also override the Equals() method.

Restricted Operators
Some operators either cannot be overloaded or depend on other operators being overloaded. The following 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.

Inheritance
Introduction to Inheritance
Definition
Imagine you create a class used to process calculations for a circle. The class may appear as follows: 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.55 Diameter: 51.1 Circmuference: 160.535249 Area: 2050.837805975 After creating this class, imagine you want to create another class used to process a sphere. You may start thinking of creating a new class and redefining the members similar to those that belong to 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 that another class can use, you can create the new class that is based on the old one: this is the foundation 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 that provides the fundamental definition or behavior you need. There is nothing magical about such a class. 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 also calculate the circumference and the area of a circle. Since a sphere is primarily a 3-dimensional circle, and if you have a class for a circle already, you can simply create your sphere class that uses 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 to as 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

by an end of line. On the next line, type the Inherits keyword, followed by the name of the class on 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 can create 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 with the 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 the class' 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 available to the derived class that can use them as necessary. While other methods and classes can also use the public members of a class, the difference is that the derived class can call the public members of 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 body of 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 Function 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) 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 Sub End Class
Code File: Exercise.vb

Module Exercise

Public Function Main() As Integer Dim ball As Sphere = New Sphere ball.ShowCharacteristics() Return 0 End Function End Module This would produce: Sphere Characteristics Radius: 35.84 Diameter: 71.68 Circumference: 225.1891712 Based on the relationship between a child class and its parent, you can use Me in the child to access 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 Function 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("Radius: {0}", Me.Radius) Console.WriteLine("Diameter: {0}", Me.CalculateDiameter()) Console.WriteLine("Circumference: {0}", Me.CalculateCircumference()) Console.WriteLine("=======================================================") End Sub End Class We mentioned that, when deriving a new class based on an existing one, all public members of the parent class are accessible to its child classes. In fact, those public members are also available to all other non-child classes and external procedures of the parent class. On the other hand, when creating a class, if you think that a certain member would not need to be accessed outside of the class, 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 Function End Class After creating a class, its private members are not accessible to clients of the class, not even to the children of that class. If you attempt to access a private member of a class outside of that class, 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

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 Sub End Class

Protected Members
When creating a class that would be used as the base of other classes, in some cases, you may want to create a special relationship among a class and its eventual children. For example, you may 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 Function End Class Not just the member variables but you can also create methods as protected as long as you intend it only for the class and its children. Remember that a protected member cannot be accessed by the 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 locate those members: Me gives you access to non-Shared public and protected members of both the parent(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 Function 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}", 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

Previous

Copyright 2009-2010 FunctionX, Inc.

Next

Polymorphism
Polymorphism Fundamentals
Introduction
As mentioned already, inheritance allows you to reuse, in a child class, code that is already implemented in a parent class. In some cases, that original code will be enough. In some other cases, you will need to apply new behavior to a child class even though the parent class already has a behavior close to what you seek. Re-creating a method in a child class using the same signature method of a parent class is referred to as overriding. Based classes have the same member but implemented differently, you need to know what particular member you are referring to, the basis of polymorphism. (name and arguments, if any) of a on this, if a derived and a parent when accessing that in your code, the parent or the derived's. This is

Overriding a Method
When creating the above two classes, imagine that you want to create a method that displays the characteristics of each shape. The method would belong to its corresponding class. This can be done 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' children would override, you can (should/must) indicate this to the compiler. This is done by preceding it with the Overridable keyword. This would be done as follows: Public Class Circle Public Ovirridable Sub ShowCharacteristics()

End Sub End Class Private Class Sphere Inherits Circle Public Sub ShowCharacteristics() End Sub End Class Once the member has been marked as overridable, when implementing the child class, in order to override 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

This would produce: Circle Characteristics ======================================================= Description: 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. -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=Radius: 35.84 Diameter: 71.68 Circumference: 225.1891712 Sphere Characteristics ======================================================= Description: A sphere is a three-dimensional geometric shape based on a circle. It is constructed so that all considered points around the shape are at an equal distance from a common point called the center. Like the circle, two equally opposite points from the center are at the exact same dictance from that center. -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=Radius: 35.84 Diameter: 71.68 Circumference: 225.1891712 ======================================================= If you mark as member of a child class with Overrides, it must have a corresponding member in the 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 base class. 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 of the parent class. For example, although both the circle and the sphere have an area, their areas are not the same. A circle is a flat surface but a sphere is a volume, which makes its area very much higher. Since they use different formulas for their respective area, you should implement a new 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 Function End 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, it may 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, to make sure that you access the derived version of the member, you can hide the corresponding member of the parent class. To do this, precede the member of the child class with the Shadows 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 Function CalculateArea() As Double Return Radius * Radius * 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}", 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 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. -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=Radius: 35.84 Diameter: 71.68 Circumference: 225.1891712 Area: 4035.389947904 ======================================================= Sphere Characteristics ======================================================= Description: A sphere is a three-dimensional geometric shape based on a circle. It is constructed so that all considered points around the shape are at an equal distance from a common point called the center. Like the circle, two equally opposite points from the center are at the exact same dictance from that center. -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=Radius: 35.84 Diameter: 71.68

Circumference: 225.1891712 Area: 16141.559791616 Volume: 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 programming language. 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 of applications necessary. To provide this functionality, the .NET Framework provides a rich set of classes (and namespaces as we will see). At the highest level, the library provides the Object class that serves as the common ancestor to all classes used in the .NET Framework. In fact, any time you create a class to use in your Visual Basic application, the class is automatically derived from Object. Consider the following Square class: 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 Characteristics Side: 42.48 Perimeter: 169.92 Area: 1804.55 Although the Square class doesn't indicate that it is inheriting from any class, by virtue of belonging to a Visual Basic application, it inherits from Object. For this reason, the above code could 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 a class 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 useful functionality to its children. In fact it is equipped with only half a dozen methods. Still, this little functionality allows the various child class to interact easily or perform some operations that would require casting. All of the methods of the Object class are public, making them directly available to the descendant classes. Most are "Overridable"s, meaning if you want to use them, you should implement 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.

Because this can mean different things to different classes. The Object class provides the method named 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 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 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 be interpreted by your class, which is done by overriding it. To override this method, follow the rules of overriding a method by associating the Overrides keyword with the syntax of the method. In the 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 a string 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

Object and Classes Comparisons


Another valuable method of the Object class is called Equals. This method is used to compare two instances of a class for equality. This method is overloaded with two versions and each returns a 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 argument an 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 a class. Instead, it takes two arguments that each represents an instance of the classes that need to be 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 Object class, in most cases, to make sure it rightly behaves, you should customize its implementation in most 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 =+=")

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 Characteristics Side: 125.84 Perimeter: 503.36 Area: 15835.71 Square Characteristics Side: 125.84 Perimeter: 503.36 Area: 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 to compare two instances of the Square class. The solution to this type of problem is to override the Equals() method in your class instead of relying on the default implementation from the Object class. 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())

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 Characteristics Side: 125.84 Perimeter: 503.36 Area: 15835.71 Square Characteristics Side: 125.84 Perimeter: 503.36 Area: 15835.71 Squares Equality: True =+= First Square =+= Enter Side: 38.45 =+= Second Square =+= Enter Side: 16.82 Square Characteristics Side: 38.45 Perimeter: 153.80 Area: 1478.40 Square Characteristics Side: 16.82 Perimeter: 67.28 Area: 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 Characteristics Side: 70.68 Perimeter: 282.72 Area: 4995.66 Square Characteristics Side: 42.04 Perimeter: 168.16 Area: 1767.36 Squares Equality: False =+= First Square =+= Enter Side: 58.26 =+= Second Square =+= Enter Side: 58.26 Square Characteristics Side: 58.26 Perimeter: 233.04 Area: 3394.23 Square Characteristics Side: 58.26 Perimeter: 233.04 Area: 3394.23 Squares Equality: True Notice that, this time, the compiler knows how to perform the comparison of two Square objects using either version of the Equals() method.

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, or add constant values to dates or times. The current date is represented by a function called Date. The Date() function is used to get the system date of the computer. You can use it to display today's date, provided your computer has the correct date. The current time of the computer is represented by a function called Time. The Time() function is used 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

Class Abstraction
An Abstract Class
Introduction
It should appear to us clearly by now that inheritance is useful by allowing us to use an object that was already created but "upgrade" it with new features that were not available when the original object was born. In most cases, when creating a class, you may not thing that other classes would be inherited from it. In fact, this will usually not be your concern: you simply create a class and use it as needed. In some other cases, rather as you build your experience with Visual Basic. You may create a class that, although useful at the time, you may already think of other classes that would be based on it. This means that, at the time you are creating such a class, you would already keep inheritance in mind. Visual Basic provides various features that can assist you with creating and implementing class 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 serve one particular purpose. As an example, imagine you start creating a class you intend to use to process 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. In this case, instead of creating a different class for each shape, you can create a generalized class that these shapes can be based on. Unfortunately, these shapes, although each characterized as geometric, don't have much in common; otherwise they would not be different. One of their common characteristics is that each has a name. While the parallelogram and the triangle have a base, the rectangle and the square don't explicitly have one. Also, neither the perimeter nor the area of these shapes are calculated the same. Still, as long as you find at least one characteristic that these objects have, you can create a class that would share. In other words, you can create a class that features one or more characteristics that these objects have. Then each object would customize 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 the Microsoft Visual Basic language, to create an abstract class, you must precede its Class keyword with 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, as done 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 Function End 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 New operator. Consider the following example:
File: Exercise.vb

Module Exercise

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. This means 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 can exploit. When creating the members of such a class, you can prepare them to be overridden. You have the option of creating overridable and non-overridable members. You will make the decision based on your requirements. Sometimes when creating a particular member, you may intend all derived classes to implement their own version of the member. You must clearly indicate that any class that wants to inherit from the MustInherit class must (also) override a particular member. Such a member must be marked with the MustOverride keyword. To do this, when creating the member, precede its type with 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 MustOverride those 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 Double End Class After creating a MustInherit class, you can inherit new classes from it using the Inherits keyword 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 of the abstract that was marked as MustOverride must be overridden. Based on this, in our Square class, 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 Double End Class Public Class Square Inherits Quadrilateral Public Overrides ReadOnly Property Area() As Double Get Return 0 End Get End Property End Class In the derived class, as a new one, you can add new members as you judge them necessary. Here are examples:
File: Quadrilateral.vb

Public MustInherit Class Quadrilateral Public Function ShowDescription() As String Return "Geometric Shape" End Function

Public MustOverride ReadOnly Property Area() As Double End 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 Property End Class After deriving a new class from a MustInherit class, you can declare a variable of it and instantiate 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 Shape Side: 35.75 Area: 1278.0625 As mentioned earlier, after creating a MustInherit class, you can declare a variable of it but you cannot 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 to members that are present in the parent class. This means that this declaration gives you access to the ShowDescription() method and the Area property of the Quadrilateral class. This is illustrated in 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

End Module This would produce: -=- Square Characteristics -=Description: Geometric Shape Area: 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 previous section. 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 Shape Side: 42.68 Area: 1821.5824

Sealed Classes
All of the classes we have used so far can serve as parents of other classes. This is the default behavior of a regular class: the ability to derive a new class from it. In some cases, you may not want any class to be derived from a particular class you are creating. Such a class is referred to as sealed. 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 the NotInheritable keyword.

Interfaces
Introduction
We described abstract classes as those intended for inheritance. Another type of class designed for this purpose is referred to as an interface. An interface is a class that creates a foundation that new derived classes can use. As done for an abstract class, you can create original behavior that the 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 a foundation, as creating a structural base, that the new classes would follow, although they can customize the behavior(s) of the parent interface but the parent interface does not "decide" what the behavior of a member would be.

Interface Creation
To create an interface, you start with the Interface keyword followed by the name of the interface. 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, instead of the Inherits keyword, you use Implements followed by the name of the interface. Here is an example 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

End Class As with other classes, once you have derived the class, you can create objects from it and instantiate 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 derived classes would follow. To do this, in the body of the interface, you can create the necessary members that you want to make available to new classes. The members can be the same types of methods 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 Double End Interface The primary rule you must observe when deriving a class from an interface is that you must implement each member of the interface in the derived class. If you omit implementing a member of the parent interface, you would receive an error. When implementing a member of the interface, it must be followed by the Implements keyword, the name of the interface, the period operator, and the name of the member that it is implementing. Based on this, our Regular class can 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 Double End Interface Public Class RegularTriangle Implements ITriangle Public Public Public Public bas hgt sd1 sd2 As As As As Double Double Double 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

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.28 Height: 26.44 Area: 466.4016 In the same way, you can derive other classes from an interface. For example, from our ITriangle class, you can derive an isosceles, a right, or an equilateral triangle. Always remember that when you derive a class, you must implement all of the members of the interface. You can also add new members as you see fit.

An Interface Derived
Like a regular class, an interface can be derived from another interface but an interface cannot derive from a class. To create an interface based on another, use the Inherits keyword as we have used 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 the deriving classes would implement. Still remember that since an interface cannot implement a member, the member of the parent interface cannot be defined in a derived interface. This implement would wait for the actual class(es) that would be based on the child (or even the parent) interface. Here is an example:

File: RegularTriangle.vb

Public Interface IGeometricShape ReadOnly Property Type() As String End 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 Double End Interface After deriving a class from an interface, when defining the class, you must implement the member of the immediate interface and those of the ancestor interface(s). Here is an example:
File: RegularTriangle.vb

Public Interface IGeometricShape ReadOnly Property Type() As String End 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 Double End Interface Public Class RegularTriangle Implements ITriangle Public Public Public Public bas hgt sd1 sd2 As As As As Double Double Double 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

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 Property End 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: Triangle Triangle Type: Regular =-= Characteristics =-= Base: 35.28 Height: 26.44 Area: 466.4016

Multiple Inheritance
Multiple inheritance consists of creating a class that is based on more than one parent. In the Microsoft Visual Basic language (in fact in the .NET Framework), you cannot derive a class from more 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 the name of each interface and separate them with commas. Here is an example: Public Interface IGeometricShape ReadOnly Property Type() As String End 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 parent interface. Besides deriving from an interface, you can also create a class that is based on a class and one or more interfaces. To do this, under the line that specifies the name of the class, use the Inherits keyword to specify the name of the parent, press Enter, and use the Implements keyword to specify the name of the class that serves as the parent interface. Here is an example: Public Interface IGeometricShape ReadOnly Property Type() As String End Interface Public Interface ICalculation End Interface

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 be based on only one class.

Classes and Procedures


Introduction
In Lesson 5, we saw that a procedure was an assignment that complemented a program. We also saw that there were two types of procedures: functions and sub routines. These concepts of sub procedures 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 type End 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 be of 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 objects in 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 a function, 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,

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 can do 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 regTri End Function After defining the function, since it returns a value, when calling it, you can assign it to a variable of 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 triangle Base: 18.44 Height: 12.62 Shape Type: Triangle Triangle Type: Regular =-= Characteristics =-= Base: 18.44 Height: 12.62 Area: 116.3564

Passing a Class as Argument


Like a regular variable, a class can be passed as argument to a procedure. When a procedure receives such an argument, it can process it as necessary. All the rules we reviewed for regular variables apply to a class, as long as you keep in mind that an object has members that you may need to be aware of. When calling the procedure, make sure you pass it a value argument based on 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)

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 sub procedure 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 the argument as you see fit, unless you choose not to. When calling the procedure, pass it a valid variable 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 triangle Base: 50.05 Height: 25.52 Shape Type: Triangle Triangle Type: Regular =-= Characteristics =-= Base: 50.05 Height: 25.52 Area: 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 the value of such a locally declared variable changes, when the procedure ends, the value of the variable 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 is considered optional. To specify that an argument is optional, when creating its procedure, type the Optional keyword to the left of the argument's name and assign it the default value. All the other rules 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 procedure with 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

the same name, they cannot have the same number of argument when the arguments at each position are of the same types.

Previous

Copyright 2009-2010 FunctionX, Inc.

Home

Built-In Classes: The Object Class


Introduction
The .NET Framework is a huge library made of various classes and constants you can directly use in your application without necessarily explicitly loading an external library. To start, this main library provides a class called Object. When you create a class, it automatically inherits its primary characteristics from the parent of all classes: Object.

Equality of Two Class Variables


When you declare and initialize two variables, one of the operations you may want to subsequently perform is to compare their value. To support this operation, the Object class provides its children with a method called Equals. The Equals() method comes in two versions. The first has the following 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 other variable as argument. Here is an example: Imports System Module Exercise Public Function Main() ' First book Dim NumberOfPages1 ' Second book Dim NumberOfPages2 ' Third book Dim NumberOfPages3 As Integer As Integer = 422 As Integer = 858 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 pages The 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 can override 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 you want to compare. In both cases, if the values of the variables are similar, the Equals() method returns true. If they are different, the method returns false. If you are using the Equals() method to compare the variables of two primitive types, the comparison should be straight forward. If you want to use this methods on variables declared from your own class, you should provide your own implementation of this method.

Stringing a Class

In previous lessons, we learned that, to convert the value of a variable declared from a primitive type 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) operator to display the value(s) of class' variable to the screen. The Object class provides an alternative to this 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 more useful if you use a primitive type such as Integer, Double and their variances or a string variable. The best way to rely on it consists of overriding it in your own class if you desire to use its 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 that would hold any type of value. Because this is some type of a "universal" data type, it can also be initialized 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: 244 Professor Kabba As you can see, when an object variable is initialized, the compiler finds out the type of value that was assigned to it. This is referred to as boxing. This mechanism is transparently done in Visual Basic. 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: 244 244 This operation is referred to as unboxing. As you can see, this operation is performed transparently.

Finalizing a Variable
While a constructor, created for each class, is used to instantiate a class. The Object class provides the Finalize() method as a type of destructor.

Home

Copyright 2008-2010 FunctionX, Inc.

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. A number is referred to as random if it has been selected from a pool without a specific pattern to follow. For example, if you decide to select the value 17 from this list, if there was an exact reason that number was selected, then it is not considered random. In reality, it is difficult for a number to qualify as random. For this reason, most random numbers are referred to as pseudorandom.

Getting a Random Number


To support the ability to create or choose a random number, the .NET Framework provides the Random 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 no argument and its syntax is: Public Overridable Function Next As Integer This method generates a randomly selected integer between 0 and the MinValue value of the Integer 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: 1369872590 Press any key to continue . . . In the same way, you can call this version of the Next() method repeatedly to get random. Here is 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: 1924504148 Number: 1257846191

Number: 424740120 Number: 1009211682 Number: 544356245 Number: 708951978 Number: 759684741 Number: 1325535324 Press 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: 573991745 Press any key to continue . . . Here is another example of running the same program: Number: 334223329 Press any key to continue . . . Notice that the numbers generated are different. When creating a program that repeatedly gets a series of random numbers, you may (or may not) want the Random class to generate the same number over and over again. A seed is a constant value that controls whether a random generation would produce the same result every time it occurs. For example, using a seed, you can impose it upon the Random class to generate the same number every time the Next() method is called. To support the ability to use a seed, the Random class is equipped with a second constructor 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 to the 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: 375271809 Press any key to continue . . . Here is another example of running the same program: Number: 375271809 Press 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

Here is one example of running the program: Number: 375271809 Number: 1472524622 Number: 1605850688 Number: 1776011503 Press any key to continue . . . Here is another example of running the same program: Number: 375271809 Number: 1472524622 Number: 1605850688 Number: 1776011503 Press 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 may want to restrict the range of numbers that can be extracted. Fortunately, the Random class allows this. Using the Random class, you can generate random positive numbers up to a maximum of your 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 the Next() method. The method returns an integer. Here is an example that generates random numbers 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: 1 Number: 7 Number: 1 Number: 16 Number: 14 Number: 19 Number: 3 Number: 1 Press any key to continue . . . The above version of specify the minimum with. To support this, takes two arguments. the Next() method generates numbers starting at 0. If you want, you can and the maximum range of numbers that the Next() method must work the Random class is equipped with one more version of this method and that 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 argument holds the highest value that the Next() method can generate. Therefore, the method would operate 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: ")

Console.WriteLine(rndNumber.ToString()) Next Return 0 End Function End Module Here is an example of running the program: Number: 17 Number: 9 Number: 8 Number: 15 Number: 10 Number: 9 Number: 13 Number: 11 Press any key to continue . . .

Home

Copyright 2009-2010 FunctionX, Inc.

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 data type named Date. To create and manipulate dates, you have various options. To declare a date variable, 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 studied classes yet, we can start using DateTime. We will restrict ourselves to using it only as a data type. We know how to declare a date variable using Date. We also know that, if you already know the components of the date value you want to use, you can include them between two # signs but following the rules of a date format from the Regional Settings of Control Panel. Here is an example: 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 the language 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 a name. The name of a month is given in two formats: complete or short. These are: Month Index 1 2 3 4 5 6 7 8 9 10 11 12 Complete Name January February March April May June July August September October November December Short Name Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec

A week is a combination of 7 consecutive days of a month. Each day can be recognized by an index from 1 to 7 (1, 2, 3, 4, 5, 6, 7). The day of each index is recognized by a name. In US

English, the first day has an index of 1 is named Sunday while the last day with an index of 7 is named Monday. Like the months of a year, the days of a week have long and short names. These are: US English Day Index 1 2 3 4 5 6 7 Complete Name Sunday Monday Tuesday Wednesday Thursday Friday Saturday Short Name Sun Mon Tue Wed Thu Fri Sat

These are the default in US English. In most calculations, the Visual Basic language allows you to 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 a year 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 short name of the month in the mmm placeholder or the complete name of the month for the mmmm placeholder, followed by either an empty space or -. End the value with the year, using 2 or 4 digits. As you may know already, in US English, you can start a date with the month. In this case, you can 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 mmmm represents the complete name of a month. As mentioned already, the dd day can be expressed with 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. An alternative is to provide a date as a string. To support this, the Visual Basic language provides a function named DateValue. Its syntax is: Public Function DateValue(ByVal StringDate As String) As DateTime

When calling this function, provide a valid date as argument. The validity depends on the language of the operating system. If working in US English, you can use one of the formats we saw above. Here is an example: Public Function Main() As Integer Dim DateHired As Date DateHired = DateValue("22-Aug-2006") MsgBox("Date Hired: " & DateHired) Return 0 End Function This would produce:

A Date as Serial
An alternative to initializing a date variable is to use a function named DateSerial. Its syntax is: 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 date value, of course without the # signs. When it has been called, this function returns a Date value. 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 allowable range 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 the computer to get the century. At the time of this writing (in 2008), the century would be 20 and the specified year would be added, which would produce 2003. To be more precise and reduce any 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, the compiler would calculate the remainder of that number by 12 (that number MOD 12 = ?). The result of the integer division would be used as the number of years and added to the first argument. The remainder would be used as the month of the date value. For example, if you pass the month as 18, the integer division would produce 1, so 1 year would be added to the first 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

End Module This would produce:

As another example, if you pass the month as 226, the integer division (226 \ 12) produces 18 and that number would be added to the first argument (2003 + 18 = 2021). The remainder of 226 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 month is passed as -1, it is considered 11 (November) of the previous year and so on. If the month is passed as a number lower than -11, the compiler would calculate its integer division to 12, add 1 to that result, use that number as the year, calculate the remainder to 12, and use that result as the month. Depending on the month, the value of the day argument can be passed as a number between 1 and 28, between 1 and 29, between 1 and 30, or between 1 and 31. If the day argument is passed as a number lower than 1 or higher than 31, the compiler uses the first day of the month passed as the second argument. This is 1. If the day is passed as -1, the day is considered the last day of the previous month of the Month argument. For example, if the Month argument is passed as 4 (April) and the Day argument is passed as -1, the compiler would use 31 as the day because the last day of March is 31. If the Month argument is passed as 3 (March) and the Day argument is passed as -1, the compiler would refer to the Year argument to determine whether the year is leap or not. This would allow the compiler to use either 28 or 29 for the day value. The compiler uses this algorithm for any day value passed as the 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 uses this 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, you can 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. If the function succeeds in the conversion, it produces a Date value. If the conversion fails, it produces 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 the day. The order of these components and how they are put together to constitute a recognizable

date depend on the language and they are defined in the Language and Regional Settings in Control Panel.

The Year of a Date


The Visual Basic language supports the year of a date ranging from 1 to 9999. This means that this is the range you can consider when dealing with dates in your applications. In most operations, when creating a date, if you specify a value between 1 and 99, the compiler would use 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 more precise, 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. Its syntax 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 valid date. 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, you can specify it with 1 or 2 digits. If the month is between 1 and 9 included, you can precede it with a leading 0. If you have a date value and want to get its month, you can call the Month() function. Its syntax 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 a number 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 month of a date. Instead of getting the numeric index of the month of a date, if you want to get the name 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

This function takes one required and one optional argument. The required argument must represent 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 short name. The default is the complete name, in which case the default value of the argument is False. If you want to get the short name, pass the second argument as True. Here is an example: 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 can range from 1 to 29 (February in a leap year), from 1 to 28 (February in a non-leap year), from 1 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 numeric day 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 syntax is:

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 the operating system's language to determine the first day of the week, which in US English is Sunday. Otherwise, if you pass one of the above indexes, the function would return the corresponding 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 short name. The default value of this argument is False, which produces a complete name. If you want 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 the first 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. The Visual Basic language provides various options. The US English language supports two primary date formats known as long date and short date. You can check them in the Date property page of the Customize Regional Options accessible from the Regional Settings in Control Panel:

To support these primary formats, the Visual Basic language provides a function named FormatDateTime. 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 a member of the DateFormat enumeration. For a date, this argument can be LongDate or ShortDate. Here is an example: Public Function Main() As Integer Dim DateHired$ DateHired$ = FormatDateTime("22-Aug-2006", DateFormat.LongDate) MsgBox("Date Hired: " & DateHired) Return 0 End Function This would produce:

Using the Format Function


To support more options, the Visual Basic language provides the Format() function that we saw 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 second argument is a string that contains the formatting to apply. To create it, you use a combination of 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 0 End Function

This would produce:

Built-In Time Functions


Introduction
The Visual Basic language supports time values. To create a time value, you can declare a variable of type Date. To initialize the variable, create a valid value using the rules specified in the 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, the Visual 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 a time 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. Its syntax 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. If you 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

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 24th spatial division of a day. It is represented by a numeric value between 0 and 23. When creating a time value, you specify the hour on the left side. To get the hour of a valid time, you can call a function 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 the hour 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 value between 0 and 59. If you have a time value and want to get its minute part, you can call a function 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 function returns 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 numeric value between 0 and 59. If you have a time value and want to extract a second part from it, you can 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 represents the seconds part.

Operations on Date and Time Values


Introduction
Because dates and times are primarily considered as normal values, there are various operations you can perform on them. You can add or subtract a number of years or add or subtract a number of months, etc. The Visual Basic language provides its own mechanisms for performing such operations 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 a function named DateAdd. In the Visual Basic language, the DateAdd() function comes in two versions whose syntaxes are: Public Overloads Function DateAdd( _ ByVal Interval As DateInterval, _ ByVal Number As Double, _ ByVal DateValue As DateTime _ ) As DateTime ' -orPublic 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. It must 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. This argument will be enclosed between double quotes and can have one of the following values: Interval Used To Add

s n h w ww d y m q yyyy

Second Minute Hour Numeric Weekday Week of the Year Day Numeric Day of the Year Month Quarter Year

The Number argument specifies the number of Interval units you want to add to the DateValue value. 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 first argument 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 likelihood of a mistake, this enumeration makes it easy by allowing you to select a member of the enumeration and use an easily recognizable name. The members of the DateInterval enumeration are: String Interval s n h w ww d y m q yyyy Enumeration Member DateInterval.Second DateInterval.Minute DateInterval.Hour DateInterval.Weekday DateInterval.Day DateInterval.DayOfYear DateInterval.Month DateInterval.Quarter DateInterval.Year Used To Add Second Minute Hour Numeric Weekday Day Numeric Day of the Year Month Quarter Year

DateInterval.WeekOfYear Week of the Year

Notice that by using the DateInterval enumeration as argument, the selected interval is easier to select. 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(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 this operation, 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 time values. To help you perform this operation, the Visual Basic language provides a function named DateDiff. 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, 3 are 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 date or end time. These two arguments can also be reversed, in which case the Date2 argument can be the start date or start time and the Date1 argument would be the end date or end time. These two values must be valid date or time values The Interval argument specifies the type of value you want as a result. This argument will be enclosed between double quotes and can have one of the following values: Interval s n h w ww d y Used To Get Second Minute Hour Numeric Weekday Week of the Year Day Numeric Day of the Year

m q yyyy Here is an example: Public Module Exercise

Month Quarter Year

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 those days on another day, supply the Option1 argument using one of the following values: vbSunday, vbMonday, vbTuesday, vbWednesday, vbThursday, vbFriday, vbSaturday. There are other variances to that argument. If your calculation involves weeks or finding the number of weeks, by default, the weeks are counted starting January 1st. If you want to count your weeks starting at a different date, use the Option2 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 time values. The first argument can be specified as a string. A better idea is to use a member of the DateInterval enumeration. The last two arguments of this function are enumeration types. The fourth argument allows you to specify what day should be considered the first of the week. By default, in US English, the first day is Sunday. To change this, use a member of the FirstDayOfWeek enumeration. The members are: Enumeration Member Constant Value Description The compiler will refer to the operating system to find out what day should be the first. In US English, this should be Sunday Sunday (the default in US English) Monday Tuesday Wednesday Thursday Friday Saturday

FirstDayOfWeek.System

FirstDayOfWeek.Sunday FirstDayOfWeek.Monday FirstDayOfWeek.Tuesday FirstDayOfWeek.Wednesday FirstDayOfWeek.Thursday FirstDayOfWeek.Friday FirstDayOfWeek.Saturday

1 2 3 4 5 6 7

By default, the first week of a year is the one that includes January 1st of that year. This is how it is considered in the regular date-based calculations. If you want to change this default setting, you can use the last argument of the DateDiff() function. The value of this argument is from an enumeration named FirstWeekofYear. The members of this enumeration are: Enumeration Member Constant Value Description The compiler will refer to

FirstWeekOfYear.System

the operating system to find out what day should be the first. This should be the week that includes January 1st This will be the week that includes January 1st This will be the first week that includes at least the first 4 days of the year This will be the first week that includes the first 7 4 days of the year

FirstWeekOfYear.Jan1

FirstWeekOfYear.FirstFourDays

FirstWeekOfYear.FirstFullWeek

Home

Copyright 2008-2010 FunctionX

Visual Basic Built-In Functions: The Message Box


Introduction
A message box is a special dialog box used to display a piece of information to the user. The user cannot type anything in the message box. There are usually two kinds of message boxes you will create: 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 an example: 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 of up to 1024 characters. To display the Prompt on multiple lines, you can use either the constant vbCrLf 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 0 End Function This would produce:

The Buttons of a Message Box


The Buttons argument specifies what button(s) should display on the message box. There are different kinds of buttons available and the Visual Basic language. The Buttons options are primary members of an enumerations named MsgBoxStyle. The members of the MsgBoxStyle enumeration that produce buttons are: Button Value MsgBoxStyle.OKOnly MsgBoxStyle.OKCancel Alternative vbOKOnly vbOKCancel Numeric Value 0 1 Display

MsgBoxStyle.AbortRetryIgnore vbAbortRetryIgnore MsgBoxStyle.YesNoCancel MsgBoxStyle.YesNo MsgBoxStyle.RetryCancel vbYesNoCancel vbYesNo vbRetryCancel

2 3 4 5

When calling the MsgBox() function and specifying the button, you can use either a member of the MsgBoxStyle enumeration or one of the above constant numeric values. Here is an example that displays 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 0 End 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 the message 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 MsgBoxStyle.Critical MsgBoxStyle.Question Alternative vbCritical vbQuestion Numeric Value 16 32 48 64 Description

MsgBoxStyle.Exclamation vbExclamation MsgBoxStyle.Information vbInformation

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 can add 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 thick border, indicating that it is the default. If the user presses Enter after viewing the button, the

effect would be the same as if he had clicked the default button. If you want, you can designate another button as the default. To do this, you can use or add another member of the MsgBoxStyle enumeration. The members used to specify the default button are: Default Button Constant Alternative If the message box contains Numeric more than one button, the Value default would be 0 256 512 The first button The second button The third button

MsgBoxStyle.DefaultButton1 vbDefaultButton1 MsgBoxStyle.DefaultButton2 vbDefaultButton2 MsgBoxStyle.DefaultButton3 vbDefaultButton3

Once again, to specify a default value, use the OR operator to combine a Default Button Constant with 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 0 End Function This would produce:

These additional buttons can be used to further control what the user can do: Constant MsgBoxStyle.ApplicationModal MsgBoxStyle.SystemModal Value Effect The user must dismiss the message box before proceeding with the current database The user must dismiss this message before using 4096 any other open application of the computer 0

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 a string whose word or words you can enclose between parentheses or that you can get from a created string. The Title argument is optional. As you have seen so far, if you omit, the message box would display the name of the application on the title bar. Otherwise, if you want a custom title, you can provide it as the third argument to the MsgBox() function. The caption can be a simple 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 0 End Function This would produce:

Notice that the caption is now customized instead of the name of the application. The caption can also 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

user clicked on the message box. Depending on the buttons the message box is displaying, after the user has clicked, the MsgBox() function can return a value. The value can be a member of the MsgBoxResult enumeration or a constant numeric value recognized by the Visual Basic language. The value returned can be one of the following values: If the user click The function returns MsgBoxResult.OK MsgBoxResult.Cancel MsgBoxResult.Abort MsgBoxResult.Retry MsgBoxResult.Ignore MsgBoxResult.Yes MsgBoxResult.No or vbOK vbCancel vbAbort vbRetry vbIgnore vbYes vbNo Numeric Value 1 2 3 4 5 6 7

Home

Copyright 2008-2010 FunctionX, Inc.

Visual Basic Built-In Functions: Conversions


Introduction
You may recall that when studying data types, we saw that each had a corresponding function used to convert a string value or an expression to that type. As a reminder, the general syntax of the conversion functions is: ReturnType = FunctionName(Expression) The Expression could be of any kind. For example, it could be a string or expression that would produce a value such as the result of a calculation. The conversion function would take such a value, string, or expression and attempt to convert it. If the conversion is successful, the function would return a new value that is of the type specified by the ReturnType in our syntax. The conversion functions are as follows: Function Name CBool CByte CDbl CDec CInt CLng CObj CSByte CShort CSng CUInt CULng CUShort Return Type Boolean Byte Double Decimal Integer Long Object SByte Short Single UInt ULong UShort Description Converts an expression into a Boolean value Converts an expression into Byte number Converts an expression into a floating-point number with double precision Converts an expression into a decimal number Converts an expression into an integer (natural) number Converts an expression into a long integer (a large natural) number Converts an expression into an Object type Converts an expression into a signed byte Converts an expression into a short integer Converts an expression into a floating-point number with single precision Converts an expression into an unsigned integer Converts an expression into an unsigned long integer Converts an expression into an unsigned short integer

Type Conversion
Conversion functions allow you to convert a known value to a another type. Besides these functions, 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 expression or 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 what have 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 first argument 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, if the 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 be lower 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 a floating-point number, its resulting value must be convertible to an integer or a floating point number 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 a floating-point number, the second argument is a number-based data type but whose range cannot hold the resulting value of the first argument, the conversion would not be allowed (the conversion will fail):

After the CType() function has performed its conversion, it returns a value that is the same category as the second argument. For example, you can call a CType() function that converts an expression 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 by the 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 an error:

Home

Copyright 2008-2010 FunctionX, Inc.

Delegates
Delegates Fundamentals
Introduction
As done when you declare a variable, when you create and call a procedure, it uses a section of memory of the computer. This section is its address. You can access that area of memory to get to the procedure. Or, you can declare a variable that would be used to access the memory used by 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 is not 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 Delegate Sub or the Delegate Function expression. A delegate must have a name: The Name factor of this formula. The name follows the rules we have 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 this procedure 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 an example: 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 data types 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 as Shared.

Associating a Delegate to a Procedure


Before using a delegate, you must create a procedure it will be associated with. The procedure must 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 variable of 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 the AddressOf operator. To use it, type it followed by the name of the procedure that implements the delegate. Assign that expression to the variable declared from the delegate. 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 Return 0 End Function End Module After assigning the address of the procedure to the delegate's variable, you can call the delegate as 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 a delegate 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 of a 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. The delegate 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 a variable 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 can call 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 a delegate, the name you give it is considered an object. That is, the name you give to the delegate becomes an object of type Delegate. Based on the characteristics of classes, that delegate object automatically becomes equipped with methods.

Delegates and Arguments


Introduction
If you want to associate a procedure that takes arguments to a delegate, when declaring the delegate, provide the necessary argument(s) in its parentheses. Here is an example of a delegate that 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 that the procedure takes the same number of arguments. Here is an example: Imports System.Drawing Imports 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 the procedure 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 named Invoke. Therefore, to associate a method to a delegate, call this method on the variable of the delegate. 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" "Side: " & vbTab & "Area: " & vbTab & "Volume: " & vbTab Return 0 End Function End Module & vbCrLf & _ CStr(Side) & vbCrLf & _ CStr(AreaDefinition.Invoke(Side)) & vbCrLf & _ & CStr(VolDefinition.Invoke(Side)))

A Delegate Passed as Argument

Using delegates, a procedure can be indirectly passed as argument to another procedure. To proceed, 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 it were a procedure itself. This means that, when accessed in the body of the procedure, the name of the delegate must be accompanied by parentheses and if the delegate takes an argument or arguments, the argument(s) must be provided in the parentheses of the called delegate. 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 End Module After declaring a delegate, remember to define a procedure that implements the needed behavior of that delegate. Once the procedure is ready, to associate it to a delegate, declare a variable of the type of the delegate using the New operator. In the parentheses of the constructor, access the name of the associated procedure using the AddressOf operator. To access the delegate, call the 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.

Namespaces
Introduction
A namespace is a section of code that is recognized with a name. A namespace allows a programmer or a group of programmers who work with others to create code with names that don'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 file before 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 with the End Namespace expression. On the right side of the starting Namespace keyword, enter a name. 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 the namespace. In this body, you can write code as you want. For example, you can create a class in it. Here is an example: Namespace Geometry Public Class Rectangle End Class End 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 Class End Namespace

Accessing Members of a Namespace


The variables, procedures, and classes created inside a namespace can be referred to as its members. To access a member of a namespace, you can use the period operator. To do this, where you want to access the member, type the name of the namespace, followed by a period, followed by the desired member of the namespace. Here is an example: Namespace Geometry Public Class Rectangle End Class End 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 qualify it. Once the member has been qualified, you can use it as we saw in previous lessons. Here are

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 Class End 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 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 Class Public Class Triangle Public Base As Double Public Height As Double Public Function Area() As Double Return Base * Height / 2 End Function End Class End Namespace In the same way, you can create as many namespaces in as many files as you want. A namespace can 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 use it. 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 & _

"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 to use it. To do this, in the top section of the file, type Imports followed by the name of the namespace.

Nesting a Namespace
You can create one namespace inside of another namespace. This is referred to as nesting the namespace. To nest a namespace, create its body in the body of an existing namespace. Here is an example: Namespace Geometry Namespace Quadrilateral End Namespace End Namespace Inside the new namespace, you can implement the behavior you want. For example, you can create a class. The parent namespace is still its own namespace and can contain any necessary thing. 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 access a 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, and followed 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

Public Function Main() As Integer Dim Tri As Geometry.Triangle = New Geometry.Triangle Tri.Base = 36.09 Tri.Height = 28.46 MsgBox("Triangle "Base:" & "Height:" "Area:" & Characteristics" vbTab & vbTab & & vbTab & vbTab vbTab & vbTab & & vbCrLf & _ FormatNumber(Tri.Base) & vbCrLf & _ & FormatNumber(Tri.Height) & vbCrLf & _ 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 the namespace exists in a separate file and you want to import it, type the Imports keyword, followed by the name of the parent namespace, followed by a period, and followed by the nested namespace. In the same way, you can import any nested namespace, as long as you appropriately qualify its name.

The System Namespace


To make programming in Visual Basic easier, many classes were created and stored in various namespaces. Each namespace is used to provide specific instructions. One of the most regularly used namespaces in the Visual Basic language is called System. Inside of the System namespace is a class called Console. The Console class is used to display things on the console screen also called the DOS window. The Console class contains procedures to display information on the screen or to retrieve information from the user who types it in the DOS window. The procedure that is used to display text on the screen is called Write. To use Write(), inside of the parentheses, type the sentence between 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 an example: 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 the caret 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 the namespace, followed by a period, and followed by the name of the member. This technique is referred to as qualifying a member of a namespace. This can be long ins some cases. Instead of qualifying a member of a namespace every time you want to use it, you can import the namespace into the file where you want to access its member(s). Here is an example: Imports System Module Exercise

Public Function Main() As Integer Console.WriteLine() Return 0 End Function End Module

Home

Copyright 2009-2010 FunctionX, Inc.

Data Reading and Formatting


Data Reading
Introduction
The Console class uses Write() or WriteLine() to display values in the DOS window. As opposed 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 to the variable specified on the left side of the assignment operator. Read() doesn't own line, which the user would function to wait always have to assign its value to a variable. For example, it can be used on its simply means that the user is expected to type something but the value typed by not be used for any significant purpose. For example, you can use the Read() 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 performing its assignment, ReadLine() sends the caret to the next line. Otherwise, it plays the same role as the 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 your application. For example, you may want the user to provide such a string. To request a string (or any of the variables we will see in this lesson), you can call the Console.Read() or the Console.ReadLine() function and assign it to the name of the variable whose value you want to retrieve. 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

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-2005 This would produce: -/- Georgetown Cleaning Services -/Enter Customer Name: James Watson Enter Customer Phone: (410) 493-2005 ==================================== -/- Georgetown Cleaning Services -/==================================== Customer: James Watson Home 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 a string. 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 use one 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 the conversion 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

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)

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 Alton Enter Customer Phone: (202) 974-8244 Number of Shirts: 8 Number of Pants: 2 Number of Dresses: 3 The Total order is: 28.711125 Amount Tended? 30 ==================================== -/- Georgetown Cleaning Services -/==================================== Customer: Genevieve Alton Home Phone: (202) 974-8244 -----------------------------------Item Type Qty Unit/Price Sub-Total -----------------------------------Shirts 8 0.95 7.60 Pants 2 2.95 5.90 Dresses 3 4.55 13.65 -----------------------------------Total Order: 27.15 Tax Rate: 5.7500% Tax Amount: 1.561125 Net Price: 28.711125 -----------------------------------Amount Tended: 30 Difference: 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 done by 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 we mentioned in Lesson 2. By default, if you request only a date from the user and the user enters a valid date, the compiler would add the midnight value to the date. If you request only the time from the user and the user enters a valid time, the compiler would add the current date to the value. Later on, we will learn 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

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))

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 Pappas Enter Customer Phone: (301) 397-9764 Enter the order date and time (mm/dd/yyyy hh:mm AM/PM) 06/22/98 08:26 AM Number of Shirts: 2 Number of Pants: 6 Number of Dresses: 0 The Total order is: 20.727000 Amount Tended? 50 ==================================== -/- Georgetown Cleaning Services -/==================================== Customer: Alexander Pappas Home Phone: (301) 397-9764 Date & Time: 6/22/1998 8:26:00 AM -----------------------------------Item Type Qty Unit/Price Sub-Total -----------------------------------Shirts 2 0.95 1.90 Pants 6 2.95 17.70 Dresses 0 4.55 0 -----------------------------------Total Order: 19.60 Tax Rate: 5.7500% Tax Amount: 1.127000 Net Price: 20.727000 -----------------------------------Amount Tended: 50 Difference: 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, you can convert a value to a string and display it directly. To do this, you can provide two strings to the 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 that would 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 closing curly bracket "}". This combination of "{" and "}" is referred to as a placeholder You can put the placeholder anywhere inside of the string. The first placeholder must have number 0. The second must have number 1, etc. With this technique, you can create 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 want to display. It can be one value if you used only one placeholder with 0 in the first string. If you used different placeholders, you can then provide a different value for each one of them in this 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:

Full Name: Anselme Bogos Age: 15 Distance: 22.74 As mentioned already, the numeric value typed in the curly brackets of the first part is an ordered number. If you want to display more than one value, provide each incremental value in its curly brackets. 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 a meaningful 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("====================================")

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 and it's your job to convert it to the appropriate type. In reverse, if you have a value that is not a string, you can easily convert it to a string. To support this, we saw in the previous lesson that each 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 a period, 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 the compiler 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 the circumstance, you may prefer to show it as a hexadecimal value. When it comes to doubleprecision numbers, you may want to display a distance with three values on the right side of the decimal separator and in some cases, you may want to display a salary with only 2 decimal places. The System namespace provides a specific letter that you can use in the Write() or WriteLine()'s placeholder for each category of data to display. To format a value, in the placeholder of the variable or value, after the number, type a colon and one of the appropriate letter from the following table. If you are using ToString(), then, in the parentheses of ToString(), you can include a specific letter or combination inside of double-quotes. The letters and their meanings are: Character c d e f g n C D E F G N Used For Currency values Decimal numbers Scientific numeric display such as 1.45e 5 Fixed decimal numbers General and most common type of numbers Natural numbers

r x p Here are examples: Module Module1

R X P

Roundtrip formatting Hexadecimal formatting Percentages

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+002 Age: 15 Color: D96 Weekly Salary: $807.31 for 35.50 hours As you may have noticed, if you leave the parentheses of ToString() empty, the compiler would use a default formatting to display the value. As opposed to calling ToString(), you can use the above letters in the curly brackets of the first part of Write() or WriteLine(). In this case, after the number in the curly brackets, type the colon 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 Const PriceAPairOfPants As Double Const PriceOneDress As Double Const TaxRate As Double ' 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)

= = = =

0.95D 2.95D 4.55D 0.0575D

' 5.75%

' 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 McCormack Enter Customer Phone: (410) 739-2884 Enter the order date and time (mm/dd/yyyy hh:mm AM/PM) 04/09/2001 10:25 AM Number of Shirts: 5 Number of Pants: 12 Number of Dresses: 8 The Total order is: 80.951625 Amount Tended? 100 ==================================== -/- Georgetown Cleaning Services -/==================================== Customer: Gretchen McCormack Home Phone: (410) 739-2884 Date & Time: 4/9/2001 10:25:00 AM -----------------------------------Item Type Qty Unit/Price Sub-Total -----------------------------------Shirts 5 $0.95 $4.75 Pants 12 $2.95 $35.40 Dresses 8 $4.55 $36.40 -----------------------------------Total Order: $76.55 Tax Rate: 5.75 % Tax Amount: $4.40 Net Price: 80.95 -----------------------------------Amount Tended: $100.00 Difference: $19.05 ==================================== 3. Return to your programming environment

Line Formatting

In the above programs, to display a line of text, we easily used Write() or WriteLine(). To position text of different lengths one above the other, we had to "corrupt" a string by including extra-empty spaces. Such a technique is uncertain and less professional. Fortunately, you can highly format how a string or a line of text should display. The .NET Framework provides mechanisms to control the amount of space used to display a string of text and how to align that string on its line. To specify the amount of space used to display a string, you can use its placeholder in Write() or WriteLine(). To do this, in the placeholder, type the 0 or the incrementing number of the placer and its formatting character if necessary and if any. Then, type a comma followed by the number of 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 Bogos Age: 15 Distance: 22.74 The sign you provide for the width is very important. If it is positive, the line of text is aligned to the 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 compiler adds a time part to the value. Fortunately, if you want to consider only the date or only the time part, you can specify this to the compiler. To support this, the DateTime data type provides a series of letters you can use to format how its value should be displayed to the user. The character is entered in the placeholder of the DateTime variable after the 0 or the incremental numeric 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 Const PriceAPairOfPants As Double Const PriceOneDress As Double Const TaxRate As Double ' 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

= = = =

0.95D 2.95D 4.55D 0.0575D

' 5.75%

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 Calhoun Enter Customer Phone: (703) 797-1135 Enter the order date(mm/dd/yyyy): 04/12/2002 Enter the order time(hh:mm AM/PM): 2:12 PM Number of Shirts: 5 Number of Pants: 2 Number of Dresses: 1 The Total order is: $16.07 Amount Tended? 20 ==================================== -/- Georgetown Cleaning Services -/==================================== Customer: Antoinette Calhoun Home Phone: (703) 797-1135 Order Date: Friday, April 12, 2002 Order Time: 2:12 PM -----------------------------------Item Type Qty Unit/Price Sub-Total -----------------------------------Shirts 5 $0.95 $4.75 Pants 2 $2.95 $5.90 Dresses 1 $4.55 $4.55 -----------------------------------Total Order: $15.20 Tax Rate: 5.75 % Tax Amount: $0.87

Net Price: $16.07 -----------------------------------Amount Tended: $20.00 Difference: $3.93 ==================================== 3. Return to your programming environment

Previous

Copyright 2009-2010 FunctionX, Inc.

Next

Custom Libraries
Introduction
If you cannot find a function you want, you can create one and be able to use it. If you plan to use such a function over and over again in different programs, you can create a library and store the function in it. You can even create one or a series of commercial functions and be able to distribute or sell it through a library. A library is a program that contains procedures and/or other resources that other programs can use. 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 usually has 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 library can contain one or more procedures (or classes). Each procedure (or class) should implement a behavior that can eventually be useful and accessible to other procedures (or classes). The contents of a library are created exactly like those we have used so far. Everything depends on how 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 New Project button and click New Project In the Templates list of the New Project dialog box, click Class Library. Accept or specify the name and click OK. Once the starting project has been generated, write the necessary code. To compile it, on the main menu, click Build -> Build Solution. If you were working from the command prompt, 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 you use the above technique, the new library would be created using the name of the file. If you are working from the Command Prompt, to compile the project and create a custom name, use the following 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

Function Divide(ByVal x As Double, ByVal y As Double) As Double If y = 0 Then Return 0 Return x / y End Function End 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 library project. Access a sub-folder of the same name, followed by the bin sub-folder, and followed by the 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 current project. 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 current project 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.

Error Handling
Introduction to Errors
Overview
We always want to create a problem-free application, one that always behaves as expected. In reality, many things can go wrong while a program is running. As an application developer, you should predict as many bad behaviors as possible so you can take appropriate actions. To assist you with dealing with errors, the Visual Basic language provides many keywords, operators, and techniques.

Introduction to Handling Errors


To deal with errors in your code, the Visual Basic language provides various techniques. One way you can do this is to prepare your code for errors. When an error occurs, you would present a message 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 would occur. 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 an example: 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 an example: 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.50 Weekly Salary: 900.00 An error occurred when the application executed Press 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

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.85 Weekly Salary: 634.00 Press 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 problem happens. 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 GoTo expression 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 an example of running the program:

An error occurred when the application executed Press 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

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 do this, type On Error GoTo followed by the numeric label. The compiler would still jump to it when appropriate. 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 On Error GoTo expression, you must have created the label. In reality, this is not a rule. You can ask the compiler to let you deal with the error one way or another. To do this, use the On Error GoTo 0 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 dealt with it. In most cases, after dealing with the error, you must find a way to continue with a normal flow of your program. In some other cases, you may even want to ignore the error and proceed as if 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

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 identify where the program would need to resume. If you want the program to continue with an alternate value than the one 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 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 a message to the user. Then, when code resumes, where should the compiler go? After all, the problem was not solved. One way you can deal with the problem is to provide an alternative to what caused the problem, since you are supposed to know what type of problem occurred. In the case of an arithmetic calculation, imagine we know that the problem was caused by the user typing an invalid number (such as typing a name where a number was expected). Instead of letting 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

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 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: 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.85 Weekly Time: 42.50 Weekly Salary: 886.13 Press any key to continue . . . Here is another example of running the program:

An error occurred when the application executed Hourly Salary: 0.00 Weekly Time: 38.00 Weekly Salary: 0.00 Press any key to continue . . . Here is one more example of running the program:

An error occurred when the application executed An error occurred when the application executed Hourly Salary: 0.00 Weekly Time: 0.00 Weekly Salary: 0.00 Press any key to continue . . .

Types of Error
Introduction
In our introductions to errors, we mostly anticipated only problems related to arithmetic calculations. In reality, a program can face various categories of bad occurrences. The more problems you prepare for, the least headaches you will have. Problems are divided in two broad categories.

Syntax Errors
A syntax error occurs if your code tries to perform an operation that the Visual Basic language does not allow. These errors are probably the easiest to locate because the Code Editor is configured 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, the Code 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

this case), the Code Editor would show it right away. This type of error is pointed out for every keyword and operator you try to use. Notice that, in the above example, we used a valid keyword but at the wrong time. If you mistype a keyword or an operator, you would receive an error. Fortunately, the Code Editor is equipped to know 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. For example, if you are creating a binary arithmetic expression that expects a second operand after the 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 was complete. This resulted in an error. These are just a few types of syntax errors you may encounter. As mentioned already, if you use the 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 does not allow. In some cases, only your application would crash. In some other cases, the user may receive a more serious error. As its name indicates, a run-time error occurs when the program runs; that is, after you have created your application. Fortunately, during the testing phase, you may encounter some of the errors so you can fix them before distributing your application. Some other errors may not occur even if you test your application. 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 your computer while locating them from the E: drive. Without paying attention, after distributing your application, the user's computer may not have an E: drive and, when trying to display the pictures, 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 not allow. An example is division by 0 (the Intel and AMD processors are equipped not to allow

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 an Integer 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 a performed operation that produces a value the variable cannot hold As you may imagine, because run-time errors occur after the application has been described as ready, some of these errors can be difficult to identify. Some other errors depend on the platform that 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. You never have to declare a variable for this class. An Err object is available whenever you start creating 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 you with identifying a problem, the Err class is equipped with a property named Number. This property 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. Because there are many types of errors, there are also many numbers, so much that we cannot review all of them. We can only mention some of them when we encounter them. When a property number. then ask program runs, to find out what type of error occurred, you can question the Number of the Err object to find out whether the error that has just occurred holds this or that To do this, you can use an If...Then conditional statement to check the number. You can 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:

Hourly Salary: 0.00 Weekly Time: 38.50 Weekly Salary: 0.00 Press any key to continue . . .

The Error Message


As mentioned already, there are many errors and therefore many numbers held by the Number property of the Err object. As a result, just knowing an error number can be vague. To further assist you with decrypting an error, the Err object provides a property named Description. This property holds a short message about the error number. This property works along with the Number 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 equivalent Description 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:

Hourly Salary: 0.00 Weekly Time: 40.00 Weekly Salary: 0.00 Press any key to continue . . . In some cases, the error message will not be explicit enough, especially if a user simply reads it to you over the phone. The alternative is to create your own message in the language you easily understand, as we did earlier. If you want, you can also display a message that combines the Err.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 be able to easily identify the source of error. To assist you with this, the Err object is equipped with a property named Source. To identify the application that caused an error, you can inquire about the value of this property.

Previous

Copyright 2009-2010 FunctionX, Inc.

Home

Events
Introduction
In a typical application, every class is mostly meant to interact with others, either to request values and methods of the other classes or to provide other classes with some values or a behavior they need. When a class A requests a value or service from another class B, class A is referred to as a client of class B. This relationship is important not simply because it establishes a relationship between both classes but also because class B should be ready to provide the value or behavior that a client needs at a certain time. While a class B is asked to provide some values to, or perform some assignment(s) for, another class A, many things would happen. In fact, there is an order that the actions should follow. For example, during the lifetime of a program, that is, while a program is running, a class may be holding a value it can provide to its client but at another time, that value may not be available anymore, for any reason; nothing strange, this is just the ways it happens. Because different things can happen to a class B while a program is running, and because only class B would be aware of these, it must be able to signal to the other classes when there is a change. This is the basis of events: An event is an action that occurs on an object and affects it in a way that its clients must be made aware of.

Event Creation
An event is declared like a pseudo-procedure. To actually declare an event, you use the Event keyword with the following formula: [modifier] Event Name(Argument) The modifier can be Public, Private, Protected, or Friend. The Event keyword is required. It is followed 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 to raise the event. To assist you with this, the Visual Basic language provides the RaiseEvent operator. 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 have declared 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 first create the delegate. Once the delegate and the event have been declared, you can hook up the delegate to the event. Then when the appropriate action occurs, the event fires. At that time, the procedure that implements the delegate runs. Before using an event, you must specify the procedure that will carry the event. This procedure is referred to as a handler. To implement this behavior, the event must return a value, and that value must be the delegate that implements the desired behavior. Obviously you must first have created a procedure. Here is an example:

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 used to specify the name of the event that is being dealt with. The Procedure factor is the name of the procedure 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 can use the RaiseEvent operator with the following formula: RaiseEvent EventName() The RaiseEvent operator is required. The EventName placeholder is used to specify the name of the 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, an event can take an argument. The primary rule to follow is that both its delegate and the procedure associated with it must take the same type of event. The second rule is that, when raising the event, 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 primary rules are the same as those for a single parameter. You just have to remember that you are dealing 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)

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 as argument.

Home

Copyright 2009-2010 FunctionX, Inc.

Errors and Exceptions: Introduction to Errors and Debugging


Errors in a Program
Introduction
Problems happen in a program. Some of them manifest themselves while you are developing your project. Some others would show up during the lifetime of your application. This seams to be an avoidable fact of life. The errors your program will encounter can be classified in three categories: 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, the Visual 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 Code Editor of Microsoft Visual Basic. The Code Editor of Microsoft Visual Basic makes it easy to be aware of syntax errors as soon as they occur: When you start typing code, the IntelliSense starts building a list of words that match the first characters and those that include the characters already typed:

If you see a word you need and it is highlighted, you can press Enter to select it. You can also double-click the word from the list. If the list is long and the word does not appear yet, you can 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 underlining the 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 that variable

The Visual Basic language is equipped with many operators and each operator has rules. If you misuse an operator, the section of your code would be underlined. You can position the mouse on it to see the resulting error message:

As you can see, if you create your application in Microsoft Visual Studio, the Code Editor is fully equipped with tools to assist you to detect and correct syntax errors. If you still violate a syntax rule, when you build your project, the compiler would detect the error and point out the line, the section, 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 Summary Summary Summary Summary += += += += += "============================" & vbCrLf "Loan Summary" & vbCrLf "=------------------------------------------=" & vbCrLf String.Format("Principal: {0:F}" & vbCrLf, Principal) "============================"

MsgBox(Summary) Return 0

End Function End Module

Logic Errors
A logic error occurs when the program (the code) is written fine but the result it produces is not reliable. With a logic error, the Code Editor does not see anything wrong in the document and therefore cannot point out a problem. One of the worse types of logic errors is one that makes a computer crash sometimes, regularly, or unpredictably, while there is nothing obviously wrong in the code. Logic errors are, or can be, difficult to spot because you will have to know for sure that the result is wrong and why (and sometimes worse, you will have to agree or accept that it is your program that is causing a problem in the computer; imagine a user reports that her computer crashes every time she starts the application you created). Because you or the user of your program would know with 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 to identify problems. Debugging is the ability to monitor the behavior of a variable, a function, or another item throughout a program. Microsoft Visual Basic provides many features to perform debugging operations. The debugger is the program you use to debug your code. The code or application that you are debugging is called the debuggee. Probably the most fundamental way of examining code is to read every word and every line, with your eyes, using your experience as a programmer. This can work for short code written in one file and in one class. If the code to examine covers many pages or many files, it could be aweful and tiresome to examine code with your eyes line by line. Fortunately, to assist you with this operation, Microsoft Visual Studio provides various tools and windows that you use, one window or a combination of objects. One of the tools you can use is the Standard toolbar that is equipped with 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 on Debug, 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 Microsoft Visual 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

One of the primary pieces of information you want to get is the value that a variable is holding. A window named Locals can be used to show that value. Normally, when you start debugging, the Locals window shows automatically. During debugging, if the Locals window is hidden, to display it: 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 to each 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 is being debugged. If the variable is a class, a + button appears to its left, indicating that it has fields (member variables):

In this case, to show the variables, that is, to expand the node, click the + button. This would show the fields under the variable name and the name of the class between curly brackets under the Value column:

The Value columns shows the value of each variable. When debugging starts, each variable shows its default value. As debugging progresses, when a variable acquires a new value, the Locals window updates it in the Value column. In some cases, instead of the debugger changing the value, 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 the class 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 execute one line at a time and see the results. To support this operation, the debugger provides what is referred 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

When code is being stepped into, the margin corresponding to the line that is being examined display 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

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 Summary Summary Summary Summary 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: = "Watts A Loan?" & vbCrLf += "========================" & vbCrLf += "Loan Summary" & vbCrLf += "-------------------------------------" & vbCrLf += "Principal:" & vbTab & vbTab & Principal.ToString("F") &

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

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

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 to pause, for any reason you judge necessary. This approach is useful if you have checked code up to a certain point and it looked alright. If you are not sure about code starting at a certain point, this can 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 To Cursor 2. When requested, enter the following values. Press Enter after entering each value. While you are entering them, check the moving button in the Code Editor and observe the values in the Locals window: Principal Interest Rate Period 2450.00 10.15 28

3. Press F5 to continue

Breakpoints
A breakpoint on a line is the code where you want the exection to suspend. You must explicitly specify 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 code executes and reaches that line, it would pause and let you know by drawing a right-pointing yellow button . 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 Delete Breakpoint 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 in your code, execution would pause at each one of them. At any time, you can remove one or all breakpoints. 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

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 Interest Rate Period 1500 15.55 24

5. Press F5 to continue

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 the mouse on Breakpoints, and click Insert Breakpoint

11. To execute, press F5 12. Click OK on the message box. Notice the first breakpoint has changed

13. To continue, press F5 14. When asked, enter the values as follows and press Enter after each Principal Interest Rate Period 17500 9.75 48

15. Press F5 to continue

16. Click OK to close the message box

Stepping to Breakpoints
You can combine the Step Into feature with breakpoints. That is, you can examine each code line after line until you get to a specific line. This allows you to monitor the values of variables and see their 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. This also allows you to know if a procedure is behaving as expected. Once you have established that a procedure is alright, you may want to skip it. Instead of executing one line at a time, the debugger allows you to execute a whole procedure at a time or to execute the lines in some procedures 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't have any problem. When debugging, you choose what procedures to step into and which ones to step 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

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 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 the starting 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 visits each line 8. Click the Step Into button function again three times to complete debugging the GetPrincipal() four times

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 12. Click OK on the message box 13. Click the Step Into button twice until the yellow margin button is positioned on the Principal = 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 four times

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() function line 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 the Principal = GetPrincipal() line 30. To avoid debugging line after line in the GetPrincipal() function, on the main menu, click Debug -> 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

Home

Copyright 2010 FunctionX, Inc.

Errors and Exceptions: Options on Debugging


Debugging and Separate Files
Introduction
In the previous sections, we dealt with one or a few procedure in only one file. As you know already, a program can use many files, some files come from the .NET Framework you create the others as you judge them necessary for your project. As a result, when debugging, you can consider files that are linked at one time or another. The process of debugging is primarily the same. You just have to keep in mind that you are dealing with different files. This has some consequences 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 Sub End 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 Function End 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:

Public Class LoanInformation Public Principal As Double Public InterestRate As Double Public Period As Double Public InterestAmount As Double Public FutureValue As Double End 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: 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

Using Separate Files


Instead of just one class or one file, we have learned that, to organize your project, you can create classes in different files. When you debug a project that uses different files that contain procedures and classes, the debugger is aware of the objects and where they are located. As we will learn later, there are various windows that assist you with identifying the objects of your project. As a result, the tools such as the Locals window display their contents accordingly.

As you know already, the starting point of a Visual Basic application is the Main() procedure. If you start debugging an application that uses many code files, the debugger must first identify the file that contains the Main() procedure. If you are debugging a normal console application and if the 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 F8 Notice 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 member variables of the class

9. To continue debugging, on the Standard toolbar, click the Step Into button debug the Employee class and observe the values in the Locals window 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

continually to

10. Continue stepping into until the debugger switches back to the LoanEvaluation.vb file

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

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 the Locals window 47. When the message box comes up, review it and click OK

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 mistake in your code, it would come up. The Error List is a window that displays the list of the current errors in your code. Most of the times, the Error List is present, usually below the Code Editor. At any 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 it showing, you can click its AutoHide button. The Error List uses two sequences of how it decides to show the errors. While writing your code, if the live parser, which continuously runs while you are writing your code, finds a problem, it makes a list of all types of violations, even if there is only one mistake, or there appears to be only one mistake. It shows the list in a table:

Another sequence or a different list may gets created if you build your code. This time, it would be the debugger's list. It is important to know that one mistake could be violating more than one rule of the Visual Basic language. As seen in our introduction to syntax errors, if you are using Microsoft Visual Basic (whether Microsoft Visual Basic 2010 Express or Microsoft Visual Studio), while you are writing your code, if the parser senses a problem, it underlines the section in the Code Editor and the Error List shows its 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 columns to show or hide, right-click anywhere in the body of the Error List and position the mouse on Show 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 can arrange the order based on a column of your choice. To do this, right-click any entry in the Error List, 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. The parser and the Error List make an effort to point the actual problem. Sometimes, the error pointed 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 is impossible to list all types of errors or all possible types of errors. With experience, you will know 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 display the 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 the problem occurrent. Also with experience, you will find out that the Error List sometimes shows where 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 be valuable if you are working on many projects, or rather on a solution that includes many projects

To jump to an error from the Error List, locate the error and double-click it. The caret would be positioned to that Line number, that character Column or word, and in that File of that Project. If you correct the problem and if the parser concludes that your correction is fine, the error would be automatically 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 Immediate window: 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. An expression you write should start with a question mark but in some cases you can omit that symbol. Because the Immediate window is a text editor, you can copy code from somewhere else and paste it in it. If the immediate window starts being crowded, to empty it, you can right-click inside the window and click Clear All. After typing or pasting the expression, press Enter. The next line would show the result. For example, imagine you want to test an arithmetic operation such as the addition of 248.49 and 57.26, you would type ?248.49 + 57.26 (the empty spaces are optional and you can include as many 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. That is, before testing a variable, create a function or use the Main() function and declare the variable in it. If you try testing a variable that is not declared, you would receive an error. One way you can test a variable consists of assigning a certain value, probably a wrong value (called a test value), to it and observe the result. You can start the assignment expression with a question mark but that mark is not necessary. Here is an example:

The Immediate window allows you to test the value that a variable is currently holding. To get this information, 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:

Another test you can perform on a variable consists of adding a value to it to increase it or subtracting a value from it. To test a procedure in the Immediate window, it must be a function. To get the value that a function is currently returning, type its name preceded by a question mark in the Immediate window and press Enter. Here is an example:

In the same way, you can create more elaborate functions and test them in the Immediate window.

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: 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 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

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

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 are holding on the current and the preceding lines. To give you this information, Microsoft Visual Studio 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, on the 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 test the behavior of that variable is to test its value as it circumstancially changes time after time. The Watch window is an object that allows you to monitor the values that a variable (or many variables) holds (or have) in various parts of a method. To get the Watch window, start debugging your application (Debug -> Start Debugging or Debug -

> Step Into). The Watch window would appear, usually next to the Locals window. The Watch window appears as a table with three columns. Their roles will be obvious to you once the window contains something. To actually use the services of a Watch window, you must create one or more entries, which are referred to as watches. Before creating a watch, you must start stepping into your code, which is done by clicking Debug -> Step Into or by pressing F8 (Microsoft Visual Studio) or F11 (Microsoft Visual Basic 2010 Express). If the Watch window doesn't display in Microsoft Visual Basic 2010 Express, 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 Microsoft Visual Basic versions, in the Watch window, double-click under the Name header, type either the name of the variable only or an expression that has the variable and an operation, then press Enter. After creating the desired entries in the Watch window, continue debugging. You will see the values being 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 all entries in the window. To remove an entry, right-click it and click Delete Watch. To remove all entries, 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

Debug -> Windows -> Watch. If you are using Microsoft Visual Studio, on the Debug toolbar, click Watch 1 (if the Debug 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 and press Enter 5. Click under HourlySalary + 0.55, type TimeWorked * HourlySalary and press the down arrow 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 press Enter 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 being examined: To know the procedure inside of which the current execution is proceeding, you can look into the Code Editor To know the line whose code is executing, in the Code Editor, you can see a yellow rightpointing arrow on its margin Since the lines of code are numbered, to know the number of the line of code that is currently

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 Visual Studio 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 -> Close Project (Microsoft Visual Basic 2010 Express) 2. When asked whether you want to save, click Discard

Home

Copyright 2010 FunctionX, Inc.

Error Handling
Error Handling
Overview
When using your application, a user may encounter various types of problems, some of which could come from you by some negligence when you worked on the project. Some other problems could occur only at the time the application is being used. Some other problems could be caused by the computer on which the application is being used. While developing your application, you should 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 expression in your code. It could be that you misspelled a keyword such as ByVel instead of ByVal. It could 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 while you are writing your code, giving up time to fix them. There are other syntax errors that the IDE 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 compiler intercepts, stops, and lets you know. For this reason, syntax errors are almost the easiest to fix. 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 the user. The time period a person is using an application is called run-time. There are different types 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 the user but you forget to ship the picture or the directory of the picture indicated in your code becomes different when a user opens your application. In this case, when you compiled and executed 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 occurring and why. 3. Logic Errors: These are errors that don't fit in any of the above categories. They could be caused by the user misusing your application, a problem with the computer on which the application is running while the same application is working fine in another computer. Because logic 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 possible and 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 be unusual 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 help you detect syntax errors and fix them. If you are using Notepad and the free vbc compiler as we have done so far, you can start by paying attention to your code. When you think everything is fine, compile your code. If there is a syntax error, the compiler will let you know. If there is no syntax error, the compilation will be over and the executable will be ready. You can then execute the application to see the result. If the user is not asked to provide value(s), you are less likely to get a run-time error. A run-time error is one that occurs when using your application. Suppose you write the following code: 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() Return 0 End Function End Module Here is an example of executing it: Enter a number: 246.88 246.88 * 2 = 493.76 The first thing your should do is to imagine what could cause a problem. If you think there is such a possibility, start by creating a label that could be used to transfer code if a problem occurs. 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() 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 to jump to that label. Otherwise, as in this case, the label section would always execute. Here is an example of running the above version: Enter a number: 12.46 12.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 the compiler from reaching this section if not directed so, you can add an Exit Sub line above the label 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 be reached.

In Case Of Error, Jump To Label


The above program will compile fine. When executing it, imagine that the user types an inappropriate value such as 24$.58 instead of 244.58. In this case, the value is not a number and the program would "crash" and let you know that there was a problem. If you have some experience, you would know what the problem was, otherwise, you would face a vague explanation. The short story is that the compiler couldn't continue because, in this case, it could not multiply 24$.58 by 2.

If a problem occurs when a person is using your program, the compiler may display a nasty and insignificant message to the user who would not know what to do with it. Therefore, you can start by 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 made for an error instead of being a regular label. The label should also reflect the name of the procedure. 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 of the procedure but before the line that could cause the problem, type On Error GoTo followed by the 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$.58 In Main(): The operation could not be executed When the On Error GoTo statement is used, this indicates to the compiler that if any type of error occurs while the code of this procedure is executed, it should transfer the compilation to the label. In this case, as soon as something bad happens, the compiler marks the area where the problem occurred, skips the normal code and jumps to the label indicated by the On Error GoTo line. After the section of that label is executed, the compiler returns where the error occurred. If there is nothing to solve the problem, the compiler continues down but without executing the lines of 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 of a problem. The alternative is to specify a numbered label instead of a lettered label. Here is an example: 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()

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: 25G In Main(): The operation could not be executed Press any key to continue . . .

Resume
If a problem occurs in your code and you provide a label to display a friendly message as done above, the compiler would display the message and exit from the procedure. If this happens, as mentioned above, when the compiler returns where the problem occurred, you can provide an alternate. For example, in our program, if the user provides an inappropriate value that causes the error, 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 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") Return 0 End Function End Module When an error occurs, if you want the program to continue with with an alternate value than the one 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 line of code that caused the problem, it would use 0 as a substitute to the inappropriate value. Here is an example of running the above program: Enter a number: 24$.58 In Main(): The operation could not be executed 0 * 2 = 0

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.58 244.58 * 2 = 489.16 Here is another example of running the same program: Enter a number: 24$.58 Invalid Number: The value you provided is inappropriate 10 will be used instead 10 * 2 = 20

The Err Object


To support error handling, Visual Basic provides a global variable named Err. This allows you to identify the error and its description. Because an error depends on what caused it and why, the values of the Err variable also depend and are not always the same.

Home

Copyright 2005-2009 FunctionX, Inc.

Introduction to Exception Handling


Introduction
As opposed to error handling techniques used to deal with a program's problems, the Visual Basic language now supports a technique referred to as exception handling. This technique was mostly used by other languages such as C/C++, Object Pascal, C#, etc. This technique is also referred 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 Integer End 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 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

' 5.75%

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 Sub End 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 Pearson Enter Customer Phone: (301) 884-0912 Enter the order date(mm/dd/yyyy): 10/05/2009 Enter the order time(hh:mm AM/PM): 08:12 Number of Shirts: 6 Number of Pants: 4 Number of Dresses: 1 The Total order is: $23.32 Amount Tended? 25 ==================================== -/- Georgetown Cleaning Services -/==================================== Customer: Judith Pearson Home Phone: (301) 884-0912 Order Date: Monday, October 05, 2009 Order Time: 8:12 AM -----------------------------------Item Type Qty Unit/Price Sub-Total

-----------------------------------Shirts 6 0.95 5.7 Pants 4 2.95 11.8 Dresses 1 4.55 4.55 -----------------------------------Total Order: $22.05 Tax Rate: 5.75 % Tax Amount: $1.27 Net Price: $23.32 -----------------------------------Amount Tended: $25.00 Difference: $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 anticipate them and take action, the better your application will be. We have already seen that syntax errors are usually human mistakes such as misspelling, bad formulation of expressions, etc. The compiler will 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 the Try keyword and stops with the End Try statement. Between Try and End Try, there must by at least 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 code that 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 the Try section and starts looking for a Catch section. Therefore, you must always have a Catch section. If you don't, as seen on the above code, the program will not compile. A Catch section must 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 that occurs. For example, here is one example of executing the above program: Enter a number: 244.58 244.58 * 2 = 489.16 Here is another example of executing the same program: Enter a number: 24$.58

Notice that the program stops if there is any type of problem but in this case, it doesn't bother to let the user know why there is no result displayed. Because there can be various types of errors in a program, you also should make your program more intuitive and friendlier so that, when a problem occurs, the user would know the type of problem. This is also useful if somebody calls you and says that your program is not functioning right. If there is a way the user can tell what exact 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 Sub End 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 compiler transfer the processing to the next catch section. You can then use the catch section to deal with the error. 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 Function End 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

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 Sub End Class 2. Execute the application and enter the values when prompted. Here is an example: -/- Georgetown Cleaning Services -/Enter Customer Name: Alexandria Enter Customer Phone: (102) 797-8382 Enter the order date(mm/dd/yyyy): 04/02/2001 Enter the order time(hh:mm AM/PM): 09:22 AM Number of Shirts: 6 Number of Pants: W The value you typed for the number of pair or pants is not a valid number Number of Dresses: 5 The Total order is: $30.09 Amount Tended? _100D You were asked to enter an amount of money but... ==================================== -/- Georgetown Cleaning Services -/==================================== Customer: Alexandria Home Phone: (102) 797-8382 Order Date: Monday, April 02, 2001 Order Time: 9:22 AM -----------------------------------Item Type Qty Unit/Price Sub-Total -----------------------------------Shirts 6 0.95 5.70 Pants 0 2.95 0 Dresses 5 4.55 22.75 -----------------------------------Total Order: $28.45 Tax Rate: 5.75 % Tax Amount: $1.64 Net Price: $30.09 ------------------------------------

Amount Tended: $0.00 Difference: ($30.09) ==================================== 3. Close the DOS window and return to your programming environment

Home

Copyright 2005-2009 FunctionX, Inc.

.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 Basic language uses it. To support exception handling, the .NET Framework provides the Exception class. Once the compiler encounters an error, the Exception class allows you to identify the type of error and take appropriate action(s). Normally, Exception mostly serves as the general class of exceptions. Anticipating various types of problems that can occur in a program, Microsoft derived various classes from Exception to make this issue friendlier. As a result, almost any type of exception you may encounter already has a class created to deal with it. Therefore, when your program faces an exception, you can easily access the class appropriate for that error. There are so many exception classes that we cannot study or review them all. The solution we will use is to introduce or review a class when we meet its 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 Integer End 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 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())

' 5.75%

' 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 Sub End 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 Pearson Enter Customer Phone: (301) 884-0912 Enter the order date(mm/dd/yyyy): 10/05/2009 Enter the order time(hh:mm AM/PM): 08:12 Number of Shirts: 6 Number of Pants: 4 Number of Dresses: 1 The Total order is: $23.32 Amount Tended? 25 ==================================== -/- Georgetown Cleaning Services -/==================================== Customer: Judith Pearson Home Phone: (301) 884-0912 Order Date: Monday, October 05, 2009 Order Time: 8:12 AM -----------------------------------Item Type Qty Unit/Price Sub-Total -----------------------------------Shirts 6 0.95 5.7 Pants 4 2.95 11.8 Dresses 1 4.55 4.55 -----------------------------------Total Order: $22.05 Tax Rate: 5.75 % Tax Amount: $1.27 Net Price: $23.32 -----------------------------------Amount Tended: $25.00 Difference: $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. By default, an exception is first of type Exception. Based on this, a typical formula to implement exception handling is: Try ' Process the normal flow of the program here Catch Parameter As Exception ' Deal with the exception here End 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 the properties of the Exception class is called Message. This property contains a string that describes the type of error that occurred. You can then use this Exception.Message property to display an error 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 Sub End Class Here is an example of running the program: Type a number: 45KP2 Cast 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 a good indication of the type of problem that occurred. Sometimes, the message provided by the

Exception class may not appear explicit enough. In fact, you may not want to show it to the user since, as in this case, the user may not understand what the word "Cast" in this context means and why it is being used. As an alternative, you can create your own message and display it to 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 ex As Exception Console.WriteLine("The operation could not be carried because " & _ "the number you typed is not valid") End Try Return 0 End Sub End Class Here is an example of running the program: Type a number: 88D.46 The 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 Sub End Class Here is an example of running the program: Type a number: 45PK12 Cast 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 think of. There are so many of these classes that we can only mention the few that we regularly use in our application. There are two main ways you can use one of the classes of the .NET Framework. If you know for sure that a particular exception will be produced, pass its name to the Catch clause and display a custom message. The second option you have consists of using the throw keyword. We will study it later. From now on, we will try to always indicate the type of exception that could be thrown if something goes wrong in a program

InvalidCastException
When studying data formatting in Lesson 5, we saw that everything the user types into an application using the keyboard is primarily a string and that you must convert it to the appropriate type before using it. When you request a specific type of value from the user, after the user has typed it and you decide to convert it to the appropriate type using one of the built-in conversion functions (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 the InvalidCastException class. Here is a program that deals with a InvalidCastException exception: Public Class Exercise Public Function Main() As Integer Dim Number As Double Try

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 Sub End Class Here is an example of running the program: Type a number: 39W.68g You 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 Sub End 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

A computer application receives, processes, and produces values on a regular basis as the program is running. To better manage these values, as we saw when studying variables and data types in Lesson 2, the compiler uses appropriate amounts of space to store its values. It is not unusual that either you the programmer or a user of your application provide a value that is beyond the allowed range of the data type. For example, a byte uses 8 bits to store a value and a combination of 8 bits can store a number no more than 255. If you provide a value higher than 255 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 Sub End 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 the program: Enter the number of pages of the newspaper: 462 Unhandled Exception: System.OverflowException: Arithmetic operation resulted in an overflow. at Microsoft.VisualBasic.CompilerServices.ByteType.FromString(String Value) at Project5.Exercise.main() in C:\Programs\MSVB .NET 2003\Project5\Exercise.v b: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 saw that a value is passed to a conversion function for analysis. For a primitive data type, the conversion function scans the string and if the string cannot be converted into a valid character or number, the compiler usually throws an InvalidCastException exception as we saw above. Other data types such as Date also use use this technique to scan the value submitted to it. For example, if you request a date value from the user, the CDate() function scans the string to validate it. In US English, CDate() expects the user to type a string in the form m/d/yy or mm/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 Sub End Class If the user types a value that cannot be converted into a valid date, the compiler throws an FormatException exception. Here is an example of running the above program: Enter Date Hired: 04/12/2002 Date Hired: 4/12/2002 Here is another example of running the program: Enter Date Hired: 1998/10/24 Date 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 vali d DateTime. at System.DateTimeParse.GetDayOfNNY(DateTimeResult result, DateTimeRawInfo ra w, DateTimeFormatInfo dtfi) at System.DateTimeParse.ProcessTerminaltState(Int32 dps, DateTimeResult resul t, DateTimeRawInfo raw, DateTimeFormatInfo dtfi) at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyl es styles) at System.DateTime.Parse(String s, IFormatProvider provider, DateTimeStyles s tyles) 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.v b:line 8 One way you can avoid this is to guide the user about the type of expected value. Here is an example:

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 Sub End 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 most fundamental exceptions of the computer. It is addressed at the core level even by the Intel and AMD processors. It is also addressed by the operating systems at their level. It is also addressed by most, if not all, compilers. It is also addressed by most, if not, all libraries. This means that this exception is never welcomed anywhere. The .NET Framework also provides it own class to face this operation. 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 a message for the error that occurred. We also mentioned that the message of this property may not be particularly useful to a user. Fortunately, you can create your own message and pass it to the Exception. To be able to receive custom messages, the Exception class provides the following constructor: public Exception(string message) To use it, in the section that you are anticipating the error, type the throw keyword followed by a new 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 Sub End Class Here is an example of running the program: Enter First Number: 244.98 Enter Operation (+, -, *, or /): * Enter Second Number: 24.52 244.98 * 24.52 = 6006.9096 Here is another example of running the program:

Enter First Number: 405.66 Enter Operation (+, -, *, or /): Enter Second Number: 24GD Something went wrong: your operation could not be performed Here is one more example of running the program: Enter First Number: 248.12 Enter 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 to use our default Catch section. We left it up to the compiler to find out when there was a problem and we provided a Catch section to deal with it. A method with numerous or complex operations and requests can also produce different types of errors. With such a type of program, you should be able to face different problems and deal with them individually, each by its own kind. To do this, you can create different Catch sections, each made for a particular error. The formula used would be: Try ' Code to Try Catch One Type of Exception ' One Exception Catch Another Type Of Exception ' Another Exception End 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 executed If 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, that catch executes and the exception handling routine may seize. If the first Catch doesnt match 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. This continues 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 matches the 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, a valid arithmetic operator, and a number. Anything else, such an invalid number, an unexpected operator, 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 program is running. To handle the exceptions that this program could produce, you can start with the most likely problem that would occur. Trusting that a user is able to provide the two numbers that are requested, it is possible that a user would type an invalid operator. For example, for this program we 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

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 Sub End Class When this program runs, if the user provides a invalid operator, we register the operator by calling the 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 receives an Exception exception. Therefore, this Catch is executed. Here is an example of running the program: Enter First Number: 1255.85 Enter 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.85 Enter 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.05 Enter 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 the user enters the denominator as 0 (or 0.00). If this happens, the best option, and probably the only one you should consider is to display a message and get out. Fortunately, the .NET Framework provides the DivideByZeroException class to deal with an exception caused by division by zero. As done with the message passed to the Exception class, you can compose your own 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, the one 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

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 Sub End Class When running this program, if the user types a wrong operator, the compiler gets out the Try block and looks for a Catch that takes an Exception as argument. It finds the second and executes it. If the user enters two valid numbers, then the compiler finds out if the operator entered was a forward slash / used to perform a division. If the user wants to perform a division, the compiler finds out if the second operand, the denominator, is 0. If it is, we create a DivideByZeroException instance and pass our own message to it. Based on this exception, the compiler gets out of the Try block and starts looking for a Catch block that considers a DivideByZeroException exception. It finds it in the first catch. Therefore, the compiler executes it. Here is an example of executing the program: Enter First Number: 1288.24 Enter 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.85 Enter 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.82 Enter Operation (+, -, *, or /): / Enter Second Number: 0 Division by zero is not allowed

Exceptions Nesting
The calculator simulator we have studied so far performs a division as one of its assignments. We learned that, in order to perform any operation, the compiler must first make sure that the user has entered a valid operator. Provided the operator is one of those we are expecting, we also must make sure that the user typed valid numbers. Even if these two criteria are met, it was possible that the user enter 0 for the denominator. The block that is used to check for a non-zero denominator 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 is done by applying the same techniques we used to nest conditional statements. This means that you can write an exception that depends on, and is subject to, another exception. To nest an exception, write a Try block in the body of the parent exception. The nested Try block must be followed by its own Catch(es) clause. To effectively handle the exception, make sure you include an 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

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 Sub End Class Here is an example of running the program: Enter First Number: 125.55 Enter 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.55 Enter Operation (+, -, *, or /): / Enter Second Number: 0 Division by zero is not allowed

Home

Copyright 2009-2010 FunctionX, Inc.

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 represented as a group of bits. So far, if we requested information from the user, when the application exited, we lost all information that the user had entered. This is because such information was only 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 the same values available the next time the user opens the application. In some other cases, whether you request information from the user or inherently provide it to the user, you may want different people working from different computers to use or share the same data. In these and other scenarios, you must store the information somewhere and retrieve it when necessary. This is the basis of file processing.

Files
A file is a series of bytes of data that are arranged in a particular way to produce a usable document. For easy storage, location, and management, the bytes are stored on a medium such as a hard disc, a floppy disc, a compact disc, or any valid and support type of storage. When these bytes belong to a single but common entity and hold values that are stored on a medium, the group is referred to as a file. For even greater management, files can be stored in a parent object called a directory or a folder. Since a file is a unit of storage and it stores information, it has a size, which is the number of bits it uses to store its values. To manage it, a file has a location also called a path that specifies where and/or how the file can be retrieved. Also, for better management, a file has attributes that indicate what can be done on the file or that provide specific information that the programmer or the operating system can use when dealing with the file.

Streams
File processing consists of creating, storing, and/or retrieving the contents of a file from a recognizable medium. For example, it is used to save word-processed files to a hard drive, to store a presentation on floppy disk, or to open a file from a CD-ROM. A stream is the technique or means of performing file processing. In order to manage files stored in a computer, each file must be able to provide basic pieces of information about itself. This basic information is specified when the 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 can be 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 (file system of the) computer. Once the user has decided where the file would reside, there are various means of creating files that the users are trained to use. When creating a file, the user must give it a name following the rules of the operating system combined with those of the file system. The most 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 assigns basic 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 contains many 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 you can retrieve data from a stream. Stream is an abstract class, which means that you cannot use it to declare a variable in your application. As an abstract class, Stream is used as the parent of the classes that actually implement the necessary operations. You will usually use a combination of classes to perform a typical operation. For example, some classes are used to create a stream object while some others are used to write data to the created stream.

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 order Public 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

' 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)

Console.WriteLine("Total Price: {0:C}" & vbCrLf, TotalPrice) End Sub End 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 Sub End 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.vb file 7. To compile it, type vbc /out:"Ice Cream Vending Machine".exe IceCream.vb Exercise.vb and press Enter 8. To execute it, type "Ice Cream Vending Machine" and press Enter. Here is an example: Ice Cream Vending Machine What type of flavor do you want? 1 - Vanilla 2 - Cream of Cocoa 3 - Chocolate Chip 4 - Organic Strawberry 5 - Butter Pecan 6 - Cherry Coke 7 - Chocolate Brownies 8 - Caramel Au Lait 9 - Chunky Butter 10 - Chocolate Cookie Your Choice? 8 What type of container do you want? 1 - Cone 2 - Cup 3 - Bowl Your Choice? 0 Invalid Choice - Try Again! What type of container do you want? 1 - Cone 2 - Cup 3 - Bowl Your Choice? -1 Invalid Choice - Try Again! What type of container do you want? 1 - Cone 2 - Cup 3 - Bowl Your Choice? 1 Do you want an ingredient or not 1 - No Ingredient 2 - Peanuts 3 - M & M 4 - Cookies Your Choice? 5 Invalid Choice - Try Again! Do you want an ingredient or not 1 - No Ingredient 2 - Peanuts 3 - M & M 4 - Cookies Your Choice? 4 How many scoops(1, 2, or 3)? 2 Ice Cream Order Flavor: Caramel Au Lait Container: Cone Ingredient: Cookies Scoops: 2 Total 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 of operation you want to conduct. For example, you may want to create a brand new file. You may want to open an existing file. Or you may want to perform a routine operation on a file. In all or most cases, whether you are creating a new file or manipulating an existing one, you must specify the name of the file. You can do this by declaring a string variable but most classes uses to create a 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 file follows the directives of the operating system. On MS DOS and Windows 3.X (that is, prior to

Microsoft Windows 9X), the file had to use the 8.3 format. The actual name had to have a maximum of 8 characters with restrictions on the characters that could be used. The user also had to specify three characters after a period. The three characters, known as the file extension, were used by the operating system to classify the file. That was all necessary for those 8-bit and 16-bit operating systems. Various rules have changed. For example, the names of folders and files on Microsoft Windows >= 95 can have up to 255 characters. The extension of the file is mostly left to the judgment of the programmer but the files are still using extensions. Applications can also be configured 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 the MSDN web site at Windows Development\Windows Base Services\Files and I/O\SDK Documentation\Storage\Storage Overview\File Management\Creating, Deleting, and Maintaining Files\Naming a File (because it is a web site and not a book, its pages can change anytime). Based on this, if you declare a string variable to hold the name of the file, you can simply initialize the 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 Sub End 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 order Public 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 Sub End 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 Sub End Class 4. Save the file 5. Compile and execute it

1.

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 must provide a complete path where the file will reside. A path is a string that specifies the drive (such as A:, C:, or D:). The sections of a complete path as string are separated by a backslash. For example, 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 be created. 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 another folder. In this case, remember that the names of folders must be separated by backslashes. In the same way, you can declare a string variable to represent the name of an existing file that you plan to 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, the compiler would consider that the file doesn't exist. If you provide folders that don't exist in the drive, the compiler would consider that the file doesn't exist. This also means that the compiler will not create the folder(s) (the .NET Framework provides all means to create a folder but you must ask the compiler to create it; simply specifying a folder that doesn't exist will not automatically create it, even if you are creating a new file). Therefore, it is your responsibility to make sure that either the file or the path to the file is valid. As we will see in the next section, the compiler 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 the File class equipped with methods to create, save, open, copy, move, delete, or provide detailed information about, files. Based on its functionality, the File class is typically used to assist the other classes with their processing operations. To effectively provide this support, all File's methods are static which means that you will usually not need to declare a File variable to access them. One of the valuable operations that the File class can perform is to check the existence of the file you want to use. For example, if you are creating a new file, you may want to make sure it doesn't exist already because if you try to create a file that exists already, the compiler may first delete the old file before creating the new one. This could lead to unpredictable result, especially because such a file is not sent to the Recycle Bin. On the other hand, if you are trying to open a file, you should first make sure the file exists, otherwise the compiler will not be able to open a file it 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 the application. If you provide the path to the file, the compiler would check its drive, its folder(s) and the file itself. In both cases, if the file exists, the method returns true. If the compiler cannot find the file, the method returns false. It's important to know that if you provided a complete path to the 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 System Imports System.IO ' This class is used to create and manage an ice cream ' and to process an order Public 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()

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 Sub End 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 Sub End 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 to proceed. One of the options you have is to indicate the type of access that will be granted on the file. This access is specified using the FileAccess enumerator. The members of the FileAccess enumerator 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 the file

File Sharing
In standalone workstations, one person is usually able to access and open a file then perform the necessary operations on it. In networked computers, you may create a file that different people can 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 more connected workstations and all workstations save their customers orders to a common file. In this case, you must make sure that any of the computers can access the file to save an order. An

employee from one of these workstations must also be able to open the file to retrieve a customer order for any necessary reason. You can also create a situation where one file holds an inventory of the items of a store and another file holds the customers orders. Obviously one file would depend on another. Based on this, when an operation must be performed on a file, you may have to 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 system is referred to as the mode of a file. It is specified through the FileMode enumerator. The members of the FileMode Enumerator are: FileMode.Append: If the file already exists, the new data will be added to its end. If the file doesn'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 same name 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 file doesn'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 be thrown 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 the file will be kept, allowing you to write new data to it. If the file doesn't exist, an error would be thrown

Home

Copyright 2009-2010 FunctionX, Inc.

Next

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 or opening it. This basic operation can be performed using a class called FileStream. You can use a FileStream object to get a stream ready for processing. As one of the most complete classes of file processing of the .NET Framework, FileStream is equipped with all necessary properties and methods. To use it, you must first declare a variable of it. 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 argument specifies the type of operation to perform on the file. Here is an example: Imports System Imports 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 Sub End Class

Stream Writing
A streaming operation is typically used to create a stream. Once the stream is ready, you can write data to it. The writing operation is perform through various classes. One of these classes is BinaryWriter. 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, you would use one of the class' three constructors. One of its constructors (the second) has the following syntax: Public Sub New(ByVal output As Stream) This constructor takes as argument a Stream value, which could be a FileStream variable. Here is an example: Imports System Imports 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 Sub End 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 that must be written to the stream. The method is overloaded so that there is a version for each primitive data type. Here is an example that adds strings to a newly created file: Imports System Imports 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 Sub End Class

Stream Closing
When you use a stream, it requests resources from the operating system and uses them while the stream is available. When you are not using the stream anymore, you should free the resources and make them available again to the operating system so that other services can use them. This is done by closing the stream. To close a stream, you can can call the Close() method of the class(es) you were using. Here are examples: Imports System Imports 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 Sub End 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()

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.vb and 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 - Vanilla 2 - Cream of Cocoa 3 - Chocolate Chip 4 - Organic Strawberry 5 - Butter Pecan 6 - Cherry Coke 7 - Chocolate Brownies 8 - Caramel Au Lait 9 - Chunky Butter 10 - Chocolate Cookie Your Choice? 7 What type of container do you want? 1 - Cone 2 - Cup 3 - Bowl Your Choice? 1 Do you want an ingredient or not 1 - No Ingredient 2 - Peanuts 3 - M & M 4 - Cookies Your Choice? 4 How many scoops(1, 2, or 3)? 2 Ice Cream Order Flavor: Chocolate Brownies Container: Cone Ingredient: Cookies Scoops: 2 Total Price: $3.10 Do you want us to remember this order the next time you come to get your ice scream (y/n)? y Please 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 can be done using the FileStream class as follows: Imports System Imports 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 Sub End Class Once the stream is ready, you can get prepared to read data from it. To support this, you can use the BinaryReader class. This class provides two constructors. One of the constructors (the first)

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. After declaring a FileStream variable using this constructor, you can read data from it. To do this, you can call an appropriate method. This class provides an appropriate method for each primitive data type. After using the stream, you should close it to reclaim the resources it was using. This is done by calling the Close() method. Here is an example of using the mentioned methods: Imports System Imports 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 Sub End Class This would produce: James Bloch Catherina Wallace Bruce Lamont Douglas 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.vb Imports System Imports System.IO ' This class is used to create and manage an ice cream ' and to process an order Public 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 ' 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: Flavors(ChoiceFlavor)) Console.WriteLine("Container: Containers(ChoiceContainer)) Console.WriteLine("Ingredient: Ingredients(ChoiceIngredient)) Console.WriteLine("Scoops: Scoops) Console.WriteLine("Total Price: & 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 {0}", {0}", {0}", {0}", {0:C}"

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 Sub End Class Source File: Exercise.vb 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 Sub End 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.vb and 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)? y Please enter the name you previously gave to remember your order: Jane44 =-= Ice Cream Vending Machine =-= Previous Order: Jane44.icr Flavor: Chocolate Brownies Container: Cone Ingredient: Cookies Scoops: 2 Total Price: $3.10 5. Return to the IceCream.vb file

Previous

Copyright 2009-2010 FunctionX, Inc.

Next

Exception Handling in File Processing


Finally
So far, to handle exceptions, we were using the Try, Catch, and Throw keywords. These allowed 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 must allocate resources and dedicate them to the file processing operations. Additional resources may be provided for the object that is in charge of writing to, or reading from, the stream. We also saw that, when the streaming was over, we should free the resources and give them back to the operating system. To do this, we called the Close() method of the variable that was using resources. More than any other assignment, file processing is in prime need of exception handling. As we will see in the next section, during file processing, there are many things that can go wrong. For this reason, the creation and/or management of streams should be performed in a Try block to get ready to handle exceptions that would occur. Besides actually handling exceptions, SEH provides a special 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 cannot exist 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. Like catch, the Finally section is created after the Try section. Unlike Catch, Finally never has parentheses 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 is usually appropriate to free the resources that were allocated earlier. Here is an example: Imports System Imports 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 Sub End Class In the same way, you can use a Finally section to free resources used when reading from a stream: Imports System Imports 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()

fstMembers.Close() End Try End Sub End Class Of course, since the whole block of code starts with a Try section, it is used for exception handling. This means that you can add the necessary and appropriate Catch section(s) but you don'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 was alright. Unfortunately, file processing can be very strict in its assignments. Based on this, the .NET Framework provides various Exception-oriented classes to deal with almost any type of exception you 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 would be provided to the operating system, when this name is acted upon, the compiler be asked to work on the file. If the file doesn't exist, the operation cannot be carried. Furthermore, the compiler would throw an error. There are many other exceptions that can thrown as a result of something going bad during file processing: FileNotFoundException: The exception thrown when a FileNotFoundException. Here is an example of handling it: Imports System Imports 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 Sub End 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't know what caused an error, you can throw the IOException exception. file has been found is of type

Previous

Copyright 2008-2010 FunctionX, Inc.

Next

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 fundamental differences 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-versa since 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 the same name inside of the same directory. Two directories cannot have the same name inside of the 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 new location A directory or a file can be copied. One file can be copied from one directory to another. If a directory 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 operating system or someone else had already created one. You can also create a new directory. Directories are created and managed by various classes but the fundamental class is Directory. Additional operations are performed using the DirectoryInfo class. Before using or creating a directory, you can first check if it exists. This is because, if a directory already exists in the location where you want to create it, you would be prevented from creating one with the same name. In the same way, if you just decide to directly use a directory that doesn't exist, the operation you want to perform may fail because the directory would not be found. Before using or creating a directory, to check first whether it exists or not, you can call the Directory.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 method returns 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 values from primitive variables that, when grouped, belong to a file. This approach falls short when the information dealt with is managed at a class level. Fortunately, modern libraries allow file processing on classes. In other words, a variable declared from a class can be saved to a stream and then the saved object can be retrieved later or on another computer. This the basis of object serialization. This serialization works by manipulating a whole object as its own value rather than its 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 means that, to use it, you define an object and initialize it, or "fill" it, with the necessary values and any information you judge necessary. This creates a "state" of the object. It is this state that you

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 a prima candidate for value serialization. Unlike strict object serialization, but like the techniques of file processing we reviewed earlier, XML considers the value members of an object, such as its fields and properties, for serialization. This means that XML doesn't allow serializing an object as its own value, but you can implement an effective object serialization by the way you proceed.

Previous

Copyright 2009-2010 FunctionX, Inc.

Home

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. To support this operation, the File class is equipped with the Create() method that is overloaded with two versions as follows: Overloads Public Shared Function Create( _ ByVal path As String _ ) As FileStream Overloads 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 you know 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 FileStream Overloads Public Shared Function Open( _ ByVal path As String, _ ByVal mode As FileMode, _ ByVal access As FileAccess _ ) As FileStream Overloads 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 provides information 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 the name of the file, the compiler would consider the same directory of its project. Here is an example: 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, you should provide the complete path.

File Creation
The FileInfo constructor is mostly meant only to indicate that you want to use a file, whether it exists already or it would be created. Based on this, if you execute an application that has only a FileInfo 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 anything in it, which implies creating an empty file, you can call the FileInfo.Create() method. Its syntax is:

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 to write 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 write text to the file.

File Existence
When you call the FileInfo.Create() or the FileInfo.CreateText() method, if the file passed as argument, or as the file in the path of the argument, exists already, it would be deleted and a new one 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 check the value of the Boolean FileInfo.Exists property. This property holds a true value if the file exists 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 use this 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 method returns a StreamWriter object. The StreamWriter class is based on the TextWriter class that is equipped 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() method writes 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 was using 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 that a 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 that object 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 file consists of opening it to read or explore its contents. To support opening a file, the FileInfo class is 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 StreamReader class that is equipped with Read() and ReadLine() methods. As done for the StreamWriter class, 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 be performed by calling the FileInfo.Delete() method. Its syntax is: Overrides Public Sub Delete() Here is an example:

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 the FileInfo.CopyTo() method that is overloaded with two versions. The first version has the following 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 copied file. 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 its content would be applied to a new file named Federal.txt created in the My Documents folder of the local computer. When calling the first version of the FileInfo.CopyTo() method, if the file exists already, the operation would not continue and you would simply receive a message box. If you insist, you can overwrite 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 argument specifies what action to take if the file exists already in the target directory. If you want to overwrite 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 the same contents in two files. Instead of copying, if you want, you can simply move the file from one directory 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 this method, 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 date and the time the file was created. This information can be valuable in other operations such as search 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 the FileSystemInfo.get_CreationTime() property is. This would be done as follows: Dim dteCreationTime As DateTime = fleLoan.CreationTime Console.WriteLine("Date and Time Created: {0}", dteCreationTime.ToString()) Of course, by entering the appropriate format in the parentheses of the ToString() method, you can 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 was created, you can change them. To change one or both of these values, you can assign a desired DateTime 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 a team or when a particular file is regularly opened, at one particular time, you may want to know the date and time that the file was last accessed. To get this information, you can access the

FileSystemInfo.LastAccessTime property. If you are interested in know the last date and time a file was modified, you can get the value of its FileSystemInfo.LastWriteTime property. You can also change this value if you want to make sure 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 specified when creating a file. This allows the OS to catalogue the computer files. This also allows you to locate or identify a particular file you need. When reviewing or opening a file, to get its name, the FileInfo class is equipped with the Name property. 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 file when creating it. Because of the type of confusions that this can lead to, most applications assist the user with this detail. For example, when we implemented the routines that allow the user to save or open a file, we specified a default extension for the Save Dialog or the Open Dialog objects. This allows the user not to care for the extension. Based on this, some applications allow the 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 can access 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 files it 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 as its 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 the FileInfo.DirectoryName property. Besides the FileInfo.Directoryname, to know the full path to a file, you can access its FileSystemInfo.FullName property.

The Attributes of a File


Attributes are characteristics that apply to a file, defining what can be done or must be disallowed on it. The Attributes are primarily defined by, and in, the operating system, mostly when a file is created. When the user accessed or open a file, to get its attributes, you can access the value of its 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, you can 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

You might also like