Microsoft Visual Basic 2010 Tutorial
January 27, 2017 | Author: EBookTutorials | Category: N/A
Short Description
Download Microsoft Visual Basic 2010 Tutorial...
Description
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
Built-In Functions
Introduction to Procedures
Conversions
Arguments and Parameters
Int/Fix
Introduction to Built-In Functions
Format Number
Static Variables
Format Currency
Optional Arguments
Format Percent
Overloading a Procedure
Len Random Functions
Conditional Statements Boolean Values | Logical Operations Introduction to Conditional Statements Functional Conditions Conditional Selections Managing Conditional Statements
Classes Fundamentals
Topics on Classes
Introduction to Classes
The Shared Members of a Class
The Methods of a Class
Characteristics of Members of a Class
Class Construction and Destruction
Nesting a Class
Structures
The Properties of a Class Operator Overloading
Inheritance and Abstraction
Built-In Classes
Inheritance
Object
Polymorphism
Random
Class Abstraction
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. 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 h. 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.
Content downloaded from www.functionx.com
Next
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
Main()
would produce the same effect. Previous
Copyright © 2008-2010 FunctionX
Content downloaded from www.functionx.com
Next
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
AddressOf
Alias
And
AndAlso
Ansi
As
Assembly
Auto
Boolean
ByRef
Byte
ByVal
Call
Case
Catch
CBool
CByte
CChar
CDate
CDbl
CDec
Char
CInt
Class
CLng
CObj
Compare
Const
Continue
CSByte
CShort
CSng
CStr
CType
CUInt
CULng
CUShort
Custom
Date
Decimal
Declare
Default
Delegate
Dim
DirectCast
Distinct
Do
Double
Each
Else
ElseIf
End
EndIf
Enum
Equals
Erase
Error
Event
Exit
Explicit
False
Finally
For
Friend
From
Function
Get
GetType
GetXmlNamespace
GoSub
GoTo
Group By
Group Join
Handles
If
Implements
Imports
In
Inherits
Integer
Interface
Into
Is
IsFalse
IsNot
IsTrue
Join
Key
Let
Lib
Like
Long
Loop
Me
Mid
Mod
Module
MustInherit
MustOverride
MyBase
MyClass
Namespace
Narrowing
New
Next
Not
Nothing
NotInheritable
NotOverridable
Object
Of
Off
On
Operator
Option
Optional
Or
Order By
OrElse
Overloads
Overridable
Overrides
ParamArray
Partial
Preserve
Private
Property
Protected
Public
RaiseEvent
ReadOnly
ReDim
REM
RemoveHandler
Resume
Return
SByte
Select
Set
Shadows
Shared
Short
Single
Skip
Skip While
Static
Step
Stop
Strict
String
Structure
Sub
SyncLock
Take
Take While
Text
Then
Throw
To
True
Try
TryCast
TypeOf
UInteger
ULong
Unicode
UShort
Until
Using
Variant
Went
When
Where
While
Widening
With
WithEvents
WriteOnly
Xor
Although you must always avoid using keywords as names of your variables in your program, 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:
Gertrude Monay
Enter Customer Acnt #:
92-37293-30
Enter Initial Deposit:
450.00
4. When you have finished, return to your programming environment
The Colon Operator : Most of the time, to make various statements easier to read, you write each on its own line. 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
-5
-4
-3
-2
-∞
-6
-5
-4
-3
-2
-1
0 -1
1
2
3
4
5
6
+∞
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.
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: $"
Bank =-=" & vbCrLf & & CustomerName & vbCrLf & & AccountNumber & vbCrLf & & (InitialDeposit + RegularDeposit)
MsgBox(Result) End Sub End Module 2. To execute the application, press F5 3. After using the program, return to your programming environment
Multiplication * The multiplication operation allows you to add a number to itself a certain number of times 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: 286
1
0
0
0
1
1
1
Content downloaded from www.functionx.com
1
0
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
0
Bit1
0
Bit0 And Bit1
0
If a bit with value 1 is added to a bit with value 0, the result is 0 Bit0
1
Bit1
0
Bit0 And Bit1
0
If a bit with value 0 is added to a bit with value 1, the result is 0 Bit0
0
Bit1
1
Bit0 And Bit1
0
If a bit with value 1 is added to a bit with value 1, the result is 1 Bit0
1
Bit1
1
Bit0 And Bit1
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
0
0
0
1
0
0
0
1
1
1
1
0
4075
1
1
1
1
1
1
1
0
1
0
1
1
286 And 4075
0
0
0
1
0
0
0
0
1
0
1
0
Therefore, 286 And 4075 produces 100001010 which is equivalent to: Bit8
Bit7
Bit6
Bit5
Bit4
Bit3
Bit2
Bit1
Bit0
256
128
64
32
16
8
4
2
1
0
0
0
0
1
0
1
0
0
0
0
0
8
0
2
0
286 And 4075
1
256
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
0
Bit1
0
Bit0 Or Bit1
0
If a bit with value 1 is added to a bit with value 0, the result is 1 Bit0
1
Bit1
0
Bit0 Or Bit1
1
If a bit with value 0 is added to a bit with value 1, the result is 1 Bit0
0
Bit1
1
Bit0 Or Bit1
1
If a bit with value 1 is added to a bit with value 1, the result is 1 Bit0
1
Bit1
1
Bit0 Or Bit1
1
As an example, consider the number 305 bit-disjoined to 2853. The decimal number 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
0
0
0
1
0
0
1
1
0
0
0
1
2853
1
0
1
1
0
0
1
0
0
1
0
1
305 Or 2853
1
0
1
1
0
0
1
1
0
1
0
1
Content downloaded from www.functionx.com
Created by www.ebooktutorials.blogspot.in Therefore, 305 Or 2853 produces 101100110101 which is equivalent to: Bit11
Bit10
Bit9
Bit8
Bit7
Bit6
Bit5
Bit4
Bit3
Bit2
Bit1
Bit0
2048
1024
512
256
128
64
32
16
8
4
2
1
0
1
1
0
0
1
1
0
1
0
1
0
512
256
0
0
32
16
0
4
0
1
305 Or 2853
1
2048
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
0
1
Bit1
0
1
Bit0 Xor Bit1
0
0
If both bits are different, the result is 1 Bit0
0
1
Bit1
1
0
Bit0 Xor Bit1
1
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
0
0
1
0
0
1
1
0
1
0
1
0
2548
1
0
0
1
1
1
1
1
0
1
0
0
618 Xor 2548
1
0
1
1
1
0
0
1
1
1
1
0
Therefore, 305 Or 2853 produces 101110011110 which is equivalent to: Bit11
Bit10 Bit9 Bit8 Bit7 Bit6 Bit5 Bit4 Bit3 Bit2 Bit1 Bit0
Content downloaded from www.functionx.com
Created by www.ebooktutorials.blogspot.in
2048
1024
1
0
618 Xor 2548
2048
512 256 128 1
0
1
1
512 256 128
64
32
16
8
4
2
1
0
0
1
1
1
1
0
0
0
16
8
4
2
0
This means that 286 And 4075 = 2048 + 512 + 256 + 128 + 16 + 8 + 4 + 2 = 2974 This can also be programmatically calculated as follows: Module Exercise Sub Main() Dim Number1 = 618 Dim Number2 = 2548 Dim Result = Number1 Xor Number2 MsgBox("286 Xor 4075 = " & (Result)) End Sub End Module This would produce:
Left-Shifting the Bits Left shifting the bits consists of pushing each bit from right to left. You can do this by one 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 GeorgetownDryCleaningServices2 Properties 10. Click the arrow of the Application Type box and select Windows Forms Application 11. Click the Close button
to close the Property Pages window
12. To execute the program, on the main menu, click Debug -> Start Debugging 13. Enter values as follows: Customer Name:
Jeannette Sharma
Content downloaded from www.functionx.com
Created by www.ebooktutorials.blogspot.in Customer Phone:
(301) 218-9000
Order Date:
04/11/2008
Order Time
08:24
Number of Shirts:
6
Number of Pants:
4
Number of Other Items: 2
14. Enter the amount tended as 40
15. Close the message box and return to your programming environment
Nothing So far, to initialize a variable, we were using a known value. Alternatively, you can use the Nothing constant 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:
Shawn Nitty
Customer Phone:
(301) 423-7744
Order Date:
04/11/2008
Order Time
09:12
Number of Shirts:
0
Number of Pants:
2
Number of Other Items: 0 4. Enter the amount tended as 20 5. Close the message box and return to your programming environment
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:
Landry Kurtzmann
Customer Phone:
(202) 223-3325
Order Date:
04/12/2008
Order Time
07:35
Number of Shirts:
8
Number of Pants:
2
Number of Other Items: 0 4. Enter the amount tended as 50 5. Close the message box and return to your programming environment
The Public Members of a Module When working on a project, you may want to create objects or declare variables that you want to be accessible 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:
William Nessif
Customer Phone:
(301) 220-3737
Order Date:
04/12/2008
Order Time
08:26
Number of Shirts:
3
Number of Pants:
3
Number of Other Items: 3 4. Enter the amount tended as 40 5. Close the message box and return to your programming environment
Details on Declaring Variables
Declaring a Series of Variables Because a program can use different variables, you can declare each variable on its own line. Here are examples: Module Exercise Sub Main() Dim NumberOfPages As Integer Dim TownName As String Dim MagazinePrice As Double End 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
Content downloaded from www.functionx.com
Home
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:
" & TypeOfHouse & vbCrLf & " & TypeOfGarage)
Return 0 End Function End Module Here is an example of running the program:
For such a program, the numbers can be vague. 1 can be considered a general number but, in 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
e
l
e
v
i
s
i
o
n
1
2
3
4
5
6
7
8
9 10
To find out what character occupies a certain position inside of a string, you can call 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
" & Str(Number))
End Module This would produce:
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 = "République 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, _ _ 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
Value Description
vbBinaryCompare
0
Perform a binary comparison
vbTextCompare
1
Perform a textual comparison
Here is an example: Private Dim Dim Dim
Sub cmdCreate_Click() strValue1 As String strValue2 As String iComparisonValue
strValue1 = "République d'Afrique du Sud" strValue2 = "Republic of South Africa" iComparisonValue = StrComp(strValue1, strValue2, vbTextCompare) MsgBox "Comparing """ & strValue1 & """ with """ & _ strValue2 & """ produces " & CStr(iComparisonValue) End Sub This would produce:
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
% & ! # @
a Byte, Short, Int16, or In32 an Int64 or a Long a Single type a Double a Long integer
Here is an example: Function GetFullName$() End Function As mentioned already, the section between the Function and the End Function lines is 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("Enter Rectangle Length:") End Sub Private Sub GetWidth() Width = InputBox("Enter Rectangle Width:") 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
Return Type
CBool
Boolean
Description
CByte
Byte
CDbl
Double
Converts an expression into a floating-point number with double precision
CDec
Decimal
Converts an expression into a decimal number
CInt
Integer
Converts an expression into a Boolean value Converts an expression into Byte number
Converts an expression into an integer (natural) number Converts an expression into a long integer (a large natural) number
CLng
Long
CObj
Object
Converts an expression into an Object type
CSByte
SByte
Converts an expression into a signed byte
CShort
Short
Converts an expression into a short integer
CSng
Single
Converts an expression into a floating-point number with single precision
CUInt
UInt
CULng
ULong
Converts an expression into an unsigned long integer
Converts an expression into an unsigned integer
CUShort
UShort
Converts an expression into an unsigned short integer
Type Conversion Conversion functions allow you to convert a known value to a another type. Besides 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
Return Type
CBool
Boolean
Description
CByte
Byte
CDbl
Double
Converts an expression into a floating-point number with double precision
CDec
Decimal
Converts an expression into a decimal number
CInt
Integer
Converts an expression into a Boolean value Converts an expression into Byte number
Converts an expression into an integer (natural) number Converts an expression into a long integer (a large natural) number
CLng
Long
CObj
Object
Converts an expression into an Object type
CSByte
SByte
Converts an expression into a signed byte
CShort
Short
Converts an expression into a short integer
CSng
Single
Converts an expression into a floating-point number with single precision
CUInt
UInt
CULng
ULong
Converts an expression into an unsigned long integer
Converts an expression into an unsigned integer
CUShort
UShort
Converts an expression into an unsigned short integer
Type Conversion Conversion functions allow you to convert a known value to a another type. Besides 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
Return Type
Description
CBool
Boolean
CByte
Byte
Converts an expression into a Boolean value
CDbl
Double
Converts an expression into a floating-point number with double precision
CDec
Decimal
Converts an expression into a decimal number
CInt
Integer
Converts an expression into an integer (natural) number
CLng
Long
Converts an expression into Byte number
Converts an expression into a long integer (a large natural) number
CObj
Object
Converts an expression into an Object type
CSByte
SByte
Converts an expression into a signed byte
CShort
Short
Converts an expression into a short integer
CSng
Single
Converts an expression into a floating-point number with single precision
CUInt
UInt
Converts an expression into an unsigned integer
CULng
ULong
Converts an expression into an unsigned long integer
CUShort
UShort
Converts an expression into an unsigned short integer
These functions allow you to convert a known value to a another type. Besides these functions, 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 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 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:
[ ] Public [ Overloads ] Shared [ Shadows ] [ Widening | Narrowing ] Operator operatorsymbol ( operand1 [, operand2 ]) [ As [ ] 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
{0}/{1} => {2}", a, b, {0}/{1} => {2}", c, d,
Addition As Rational Subtraction As Rational Multiplication As Rational Division As Rational
Addition = FirstFraction + SecondFraction MsgBox(String.Format("Addition: {0}/{1} + {2}/{3} = {4}", a, b, c, d, Addition)) Subtraction = FirstFraction - SecondFraction MsgBox(String.Format("Addition: {0}/{1} + {2}/{3} = {4}", a, b, c, d, Subtraction)) Multiplication = FirstFraction * SecondFraction MsgBox(String.Format("Addition: {0}/{1} + {2}/{3} = {4}", a, b, c, d, Multiplication)) Division = FirstFraction / SecondFraction MsgBox(String.Format("Addition: {0}/{1} + {2}/{3} = {4}", a, b, c, d, Division)) Return 0 End Function End Module 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 >=. 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, >, 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 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
= "Watts A Loan?" & vbCrLf += "========================" & vbCrLf += "Loan Summary" & vbCrLf += "-------------------------------------" & vbCrLf += "Principal:" & vbTab & vbTab & Principal.ToString("F") &
vbCrLf Summary += "Interest Rate:" & vbTab & InterestRate.ToString("P") & vbCrLf Summary += "Period:" & vbTab & vbTab & CStr(Period * 12) & " months" & vbCrLf Summary += "Interest Amount:" & vbTab & InterestAmount.ToString("F") & vbCrLf Summary += "Future Value:" & vbTab & FutureValue.ToString("F") & vbCrLf Summary += "========================" MsgBox(Summary, MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, "Watts A Loan?") Return 0 End Function End Module 5. To restart debugging, on the main menu, click Debug -> Step Into. Notice that the Locals window displays a list of the local variables and their starting values:
6. To continue debugging, on the Standard toolbar, click the Step Into button 7. To continue debugging, press F8 twice
8. Keep pressing F8 until a message box displays
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
2450.00
Interest Rate
10.15
Period
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
1500
Interest Rate
15.55
Period
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
17500
Interest Rate
9.75
Period
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
four times
4. Click OK on the message box 5. Click the Step Into button again two times. Notice the yellow margin button is positioned on Principal = GetPrincipal() 6. Click the Step Into button and notice that the yellow-point button is positioned on 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()
9. To stop the debugging, on the Standard toolbar, click the Stop Debugging button 10. To debug, on the main menu, click Debug -> Step Into. Notice that the yellow button is positioned in the margin 11. To continue, on the Standard toolbar, click the Step Into button
four times
12. Click OK on the message box 13. Click the Step Into button twice until the yellow margin button is positioned on 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
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
continually to
10. Continue stepping into until the debugger switches back to the LoanEvaluation.vb file 11. Press F8 and notice that the IdentifyEmployee() function gets focus 12. Press F8 again twice 13. When requested, enter the Employee # as 80226 and click OK 14. Click the Step Into button 15. When asked for the first name, type David and click OK 16. Press F8 17. For the last name, type Boyton and click OK 18. Press F8 19. For the title, type Shift Supervisor and click OK. Observe the values in the Locals window
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
' 5.75%
Dim order As OrderInformation ' Each of these sub totals will be used for cleaning items Private SubTotalShirts As Double Private SubTotalPants As Double Private SubTotalDresses As Double ' Values used to process an order Private TotalOrder As Double Private TaxAmount As Double Private SalesTotal As Double Private AmountTended As Double Private Difference As Double Public Sub ProcessOrder() Console.WriteLine("-/- Georgetown Cleaning Services -/-") ' Request order information from the user Console.Write("Enter Customer Name: ") Order.CustomerName = Console.ReadLine() Console.Write("Enter Customer Phone: ") Order.HomePhone = Console.ReadLine() Console.Write("Enter the order date(mm/dd/yyyy): ") Order.OrderDate = DateTime.Parse(Console.ReadLine()) Console.Write("Enter the order time(hh:mm AM/PM): ") Order.OrderTime = DateTime.Parse(Console.ReadLine()) ' Request the quantity of each category of items Console.Write("Number of Shirts: ") order.NumberOfShirts = CInt(Console.ReadLine()) Console.Write("Number of Pants: ") order.NumberOfPants = CInt(Console.ReadLine()) Console.Write("Number of Dresses: ") order.NumberOfDresses = CInt(Console.ReadLine()) ' Perform the necessary calculations SubTotalShirts = Order.NumberOfShirts * PriceOneShirt
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
' 5.75%
Dim order As OrderInformation ' Each of these sub totals will be used for cleaning items Private SubTotalShirts As Double Private SubTotalPants As Double Private SubTotalDresses As Double ' Values used to process an order Private TotalOrder As Double Private TaxAmount As Double Private SalesTotal As Double Private AmountTended As Double Private Difference As Double Public Sub ProcessOrder() Console.WriteLine("-/- Georgetown Cleaning Services -/-") ' Request order information from the user Console.Write("Enter Customer Name: ") Order.CustomerName = Console.ReadLine() Console.Write("Enter Customer Phone: ") Order.HomePhone = Console.ReadLine() Console.Write("Enter the order date(mm/dd/yyyy): ") Order.OrderDate = DateTime.Parse(Console.ReadLine()) Console.Write("Enter the order time(hh:mm AM/PM): ") Order.OrderTime = DateTime.Parse(Console.ReadLine())
' Request the quantity of each category of items 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 doesn’t 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
{0}", {0}", {0}", {0}", {0:C}"
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 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:
file
has
been
found
is
of type
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.
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
View more...
Comments