Microsoft Visual Basic 2010 Tutorial
Microsoft Visual Basic 2010 Tutorial
Microsoft Visual Basic 2010 Tutorial
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
Built-In Functions
Conversions Int/Fix Format Number Format Currency Format Percent Len Random Functions
Conditional Statements
Boolean Values | Logical Operations Introduction to Conditional Statements Functional Conditions Conditional Selections Managing Conditional Statements
Classes
Fundamentals
Introduction to Classes The Methods of a Class Class Construction and Destruction Structures
Topics on Classes
The Shared Members of a Class Characteristics of Members of a Class Nesting a Class The Properties of a Class Operator Overloading
Built-In Classes
Object Random
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
Created by www.ebooktutorials.blogspot.in
To launch Microsoft Visual Studio 2010, you can click Start -> (All) Programs -> Microsoft Visual Studio 2010.
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
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:
Created by www.ebooktutorials.blogspot.in
f. Click Add Command... g. h. In the Categories list of the Add Command dialog box, select the category that has the button you want. For our example, that would be Debug In the Commands list, click the desired button or menu item. For our example, that would be Start Without Debugging
Created by www.ebooktutorials.blogspot.in
In the same way, you can customize any toolbar and any menu category.
Created by www.ebooktutorials.blogspot.in
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:
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:
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:
Created by www.ebooktutorials.blogspot.in
Becomes
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:
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:
Created by www.ebooktutorials.blogspot.in
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
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
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
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.
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
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.
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
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:
Created by www.ebooktutorials.blogspot.in
In the System window, click Change Settings. In the System Properties dialog box, click the Advanced tab. Click the Environment Variables button:
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:
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
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.
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.
If you are using Microsoft Visual Basic 2010 Express, in the middle list, click Console Application. Change the Name to GeneralCensus
Created by www.ebooktutorials.blogspot.in
Click OK
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:
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.
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
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.
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.
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.
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...:
Created by www.ebooktutorials.blogspot.in
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.
Created by www.ebooktutorials.blogspot.in
Sub Main() MsgBox("We are performing a general census of our population") End Sub End Module
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.
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:
Created by www.ebooktutorials.blogspot.in
Alternatively, you can start a comment with the Rem keyword. Anything on the right side of rem, Rem, or REM would not be processed. Here is an example: Module Module1 Sub Main() ' This line will not be considered as part of the code Rem I can write anything I want on this line End Sub End Module Comments are very useful and you are strongly suggested to use comments regularly. They can never hurt your code and they do not increase the size of your application. Comments can help you and other people who read your code to figure out what a particular section of code is used for, which can be helpful when you re-visit your code after months or years of not seeing it.
White Spaces
When writing code, you will have to separate different parts with spaces, like the one between Sub and Main. This is referred to as white space. The amount of space you put between two words is not important. The compiler would ignore the white spaces between words. This means that Sub Main() and Sub Main() would the same effect. In the same way Sub Main() and Sub would produce the same effect. Main()
Previous
Next
Created by www.ebooktutorials.blogspot.in
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
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.
Created by www.ebooktutorials.blogspot.in
Must be unique inside of the procedure or the module it is used in
A name cannot be one of the words reserved for the Visual Basic language's own use. These words are also called keywords. Therefore, avoid using the following words to name a variable (this list includes official Visual Basic language keywords and words or expressions you should avoid): AddHandler Ansi ByRef Catch CDbl CLng CSByte CUInt Decimal DirectCast Else End Error Finally Get Group By Imports Into Join Long Module Namespace Nothing Off Or Overrides Property ReDim SByte Short Step Sub Then TryCast UShort Went With AddressOf As Byte CBool CDec CObj CShort CULng Declare Distinct ElseIf EndIf Event For GetType Group Join In Is Key Loop MustInherit Narrowing NotInheritable On Order By ParamArray Protected REM Select Single Stop SyncLock Throw TypeOf Until When WithEvents Enum Exit Friend GetXmlNamespace Handles Inherits IsFalse Let Me MustOverride New NotOverridable Operator OrElse Partial Public RemoveHandler Set Skip Strict Take To UInteger Using Where WriteOnly Equals Explicit From GoSub If Integer IsNot Lib Mid MyBase Next Object Option Overloads Preserve RaiseEvent Resume Shadows Skip While String Take While True ULong Variant While Xor Widening Erase False Function GoTo Implements Interface IsTrue Like Mod MyClass Not Of Optional Overridable Private ReadOnly Return Shared Static Structure Text Try Unicode Alias Assembly ByVal CByte Char Compare CSng CUShort Default Do And Auto Call CChar CInt Const CStr Custom Delegate Double AndAlso Boolean Case CDate Class Continue CType Date Dim Each
Although you must always avoid using keywords as names of your variables in your program, if you insist on using one of these keywords to name something, put the word between square brackets. An example would be [True] The Visual Basic language is not case sensitive. This means that NAME, name, and Name represent the same word. This means that, in the same section (normally called scope), you cannot have two variables with the same name that differ only by their cases. This would cause a name conflict. If you declare a variable in a scope and use it later with a different case, as
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.
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
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.
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.
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.
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.
Created by www.ebooktutorials.blogspot.in
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:
Created by www.ebooktutorials.blogspot.in
Sub Main() Dim FirstName Dim LastName Dim FullName FirstName = "Francis " LastName = "Pottelson" FullName = LastName & ", " & FirstName MsgBox("First Name: " & vbTab & FirstName & vbCrLf & "Last Name: " & vbTab & LastName & vbCrLf & "Full Name: " & vbTab & FullName) End Sub This would produce:
In the same way, you can create as many vbTab combinations as necessary.
Unary Operators
Positive Unary Operator: +
Algebra uses a type of ruler to classify numbers. This ruler has a middle position of zero. The numbers on the left side of the 0 are referred to as negative while the numbers on the right side of the rulers are considered positive: - - -6 -6 -5 -5 -4 -4 -3 -3 -2 -2 -1 0 -1 1 2 3 4 5 6 + A value on the right side of 0 is considered positive. To express that a number is positive, you can write a + sign on its left. Examples are +4, +228, +90335. In this case the + symbol is called a unary operator because it acts on only one operand. The positive unary operator, when used, must be positioned on the left side of its operand, never on the right side. As a mathematical convention, when a value is positive, you don't need to express it with the + operator. Just writing the number without any symbol signifies that the number is positive. Therefore, the numbers +4, +228, and +90335 can be, and are better, expressed as 4, 228, 90335. Because the value does not display a sign, it is referred as unsigned. 1 2 3 4 5 6 +
The Negative Operator As you can see on the above ruler, in order to express any number on the left side of 0, it must be appended with a sign, namely the - symbol. Examples are -12, -448, -32706. A value accompanied by - is referred to as negative. The - sign must be typed on the left side of the number it is used to negate. Remember that if a number does not have a sign, it is considered positive. Therefore, whenever a number is negative, it MUST have a - sign. In the same way, if you want to change a value from positive to negative, you can just add a - sign to its left.
Arithmetic Operators
Content downloaded from www.functionx.com
Created by www.ebooktutorials.blogspot.in
Addition +
The addition is performed with the + sign. It is used to add one value to another. To add two numbers, such as 225 and 64, you could use 225 + 64. The result would be 289. The addition is also used to add the values of two variables as in MondayHours + TuesdayHours to get a total number of hours worked on Monday and Tuesday. Besides arithmetic operations, the + symbol can also be used to concatenate strings, that is, to add one string to another. This is done by appending one string at the end of another. Here is an example: Module Exercise Sub Main() Dim FirstName Dim LastName Dim FullName FirstName = "James " LastName = "Fame" FullName = FirstName + LastName MsgBox("Full Name: " & FullName) End Sub End Module
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.
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
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
Created by www.ebooktutorials.blogspot.in
Not 286 0 1 1 1 0 0 0 0 1
Bitwise Conjunction
Bitwise conjunction consists of adding the content of one box (a bit) to the content of another box (a bit). To support the bitwise conjunction operation, the Visual Basic language provides the And operator. To perform the bit addition on two numbers, remember that they must be converted to binary first. Then: If a bit with value 0 is added to a bit with value 0, the result is 0 Bit0 Bit1 Bit0 And Bit1 0 0 0
If a bit with value 1 is added to a bit with value 0, the result is 0 Bit0 Bit1 Bit0 And Bit1 1 0 0
If a bit with value 0 is added to a bit with value 1, the result is 0 Bit0 Bit1 Bit0 And Bit1 0 1 0
If a bit with value 1 is added to a bit with value 1, the result is 1 Bit0 Bit1 Bit0 And Bit1 1 1 1
As an example, consider the number 286 bit-added to 475. The decimal number 286 converted to binary is 100011110. The decimal number 4075 converted to binary is 111111101011. Based on the above 4 points, we can add these two numbers as follows: 286 4075 286 And 4075 0 1 0 0 1 0 0 1 0 1 1 1 0 1 0 0 1 0 0 1 0 1 0 0 1 1 1 1 0 0 1 1 1 0 1 0
Therefore, 286 And 4075 produces 100001010 which is equivalent to: Bit8 256 286 And 4075 1 256 Bit7 128 0 0 Bit6 64 0 0 Bit5 32 0 0 Bit4 16 0 0 Bit3 8 1 8 Bit2 4 0 0 Bit1 2 1 2 Bit0 1 0 0
This means that 286 And 4075 = 256 + 16 + 2 = 266 This can also be programmatically calculated as follows:
Created by www.ebooktutorials.blogspot.in
Module Exercise Sub Main() Dim Number1 = 286 Dim Number2 = 4075 Dim Result = Number1 And Number2 MsgBox("286 And 4075 = " & (Result)) End Sub End Module This would produce:
Bitwise Disjunction
Bitwise disjunction consists of disjoining one a bit from another bit. To support this operation, the Visual Basic language provides the Or operator. To perform a bitwise conjunction on two numbers, remember that they must be converted to binary first. Then: If a bit with value 0 is added to a bit with value 0, the result is 0 Bit0 Bit1 Bit0 Or Bit1 0 0 0
If a bit with value 1 is added to a bit with value 0, the result is 1 Bit0 Bit1 Bit0 Or Bit1 1 0 1
If a bit with value 0 is added to a bit with value 1, the result is 1 Bit0 Bit1 Bit0 Or Bit1 0 1 1
If a bit with value 1 is added to a bit with value 1, the result is 1 Bit0 Bit1 Bit0 Or Bit1 1 1 1
As an example, consider the number 305 bit-disjoined to 2853. The decimal number 305 converted to binary is 100110001. The decimal number 2853 converted to binary is 101100100101. Based on the above 4 points, we can disjoin these two numbers as follows: 305 2853 305 Or 2853 0 1 1 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 0 1 0 0 0 0 1 1 0 0 0 1 1 1
Created by www.ebooktutorials.blogspot.in
Therefore, 305 Or 2853 produces 101100110101 which is equivalent to: Bit11 2048 305 Or 2853 1 2048 Bit10 1024 0 0 Bit9 512 1 512 Bit8 256 1 256 Bit7 128 0 0 Bit6 64 0 0 Bit5 32 1 32 Bit4 16 1 16 Bit3 8 0 0 Bit2 4 1 4 Bit1 2 0 0 Bit0 1 1 1
This means that 286 And 4075 = 2048 + 512 + 256 + 32 + 16 + 4 + 1 = 2869 This can also be programmatically calculated as follows: Module Exercise Sub Main() Dim Number1 = 305 Dim Number2 = 2853 Dim Result = Number1 Or Number2 MsgBox("286 Or 4075 = " & (Result)) End Sub End Module This would produce:
Bitwise Exclusion
Bitwise exclusion consists of adding two bits with the following rules. To support bitwise exclusion, the Visual Basic language provides an operator named Xor: If both bits have the same value, the result is 0 Bit0 Bit1 Bit0 Xor Bit1 0 0 0 1 1 0
If both bits are different, the result is 1 Bit0 Bit1 Bit0 Xor Bit1 0 1 1 1 0 1
As an example, consider the number 618 bit-excluded from 2548. The decimal number 618 converted to binary is 1001101010. The decimal number 2548 converted to binary is 100111110100. Based on the above 2 points, we can bit-exclude these two numbers as follows: 618 2548 618 Xor 2548 0 1 1 0 0 0 1 0 1 0 1 1 0 1 1 1 1 0 1 1 0 0 1 1 1 0 1 0 1 1 1 0 1 0 0 0
Therefore, 305 Or 2853 produces 101110011110 which is equivalent to: Bit11 Bit10 Bit9 Bit8 Bit7 Bit6 Bit5 Bit4 Bit3 Bit2 Bit1 Bit0
Created by www.ebooktutorials.blogspot.in
2048 618 Xor 2548 1 2048 1024 0 0 512 256 128 1 1 1 512 256 128 64 0 0 32 0 0 16 1 16 8 1 8 4 1 4 2 1 2 1 0 0
This means that 286 And 4075 = 2048 + 512 + 256 + 128 + 16 + 8 + 4 + 2 = 2974 This can also be programmatically calculated as follows: Module Exercise Sub Main() Dim Number1 = 618 Dim Number2 = 2548 Dim Result = Number1 Xor Number2 MsgBox("286 Xor 4075 = " & (Result)) End Sub End Module This would produce:
To perform a left shift operation on these bits, you push each from its position to the left, depending on the number of pushes you want. For example, to left-shift by 1 bit, you push each bit to the left by one position. Actually, you consider the bit at position x and the bit to its left at position y. You replace the value of Bit y by the value of Bit x. If Bit x is the most right bit, it receives a value of 0. This can be illustrated as follows: Original << by 1 1 1 0 0 1 1 1 1 1 1 0 0 0 0 1 1 0 0 1 1 0
As a result, we get 10111001010. The decimal result can be calculated as follows: Bit10 1024 741 << 1 1 1024 Bit9 512 0 0 Bit8 256 1 256 Bit7 128 1 128 Bit6 64 1 64 Bit5 32 0 0 Bit4 16 0 0 Bit3 8 1 8 Bit2 4 0 0 Bit1 2 1 2 Bit0 1 0 0
Consequently, 741 << 1 = 1024 + 256 + 128 + 64 + 8 + 2 = 458 This can also be evaluated programmatically as follows: Module Exercise Sub Main() MsgBox("741 << 1 = " & (741 << 1))
Created by www.ebooktutorials.blogspot.in
End Sub End Module This would produce:
In the same way, you can push the bits to the left by more than one unit.
Previous
Next
Created by www.ebooktutorials.blogspot.in
Introduction to Variables
Variable Declaration With Type
Introduction
As we will see in the next lessons, when a user is asked to provide a value in a program, the value is primarily considered a normal group of characters, also called a string. If you intend to involve that value in an operation that is not meant for a string, you should (usually must) first convert that string to the appropriate value. Fortunately, each data type that we are going to review presents an appropriate and easy mechanism to perform this conversion. To specify the amount of memory that a variable would use, on the right side of the variable's name, you type the As keyword followed by the data type. The formula to declare such a variable is: Dim VariableName As DataType
Type Characters
To make variable declaration a little faster and even convenient, you can replace the As DataType expression with a special character that represent the intended data type. Such a character is called a type character and it depends on the data type you intend to apply to a variable. When used, the type character must be the last character of the name of the variable. We will see what characters are available and when it can be applied.
Created by www.ebooktutorials.blogspot.in
9. Click the arrow of the Application Type box and select Windows Forms Application 10. Click the Close button to close the Property Pages window
A Byte
A byte is a group of 8 bits. Since each bit can have a value or either 1 or 0. The total number of possible combinations of 8 bits is 2 7 + 2 6 + 2 5 + 2 4 + 2 3 + 2 2 + 2 1 + 2 0 = 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 255. Since all bits can have values of 0 each, a byte can have values from 0 to 255. Therefore, a byte can hold a small natural positive number that ranges from 0 to 255. To declare a variable for a small number, use the Byte keyword. Here is an example: Module Exercise Sub Main() Dim StudentAge As Byte End Sub End Module A Byte variable is initialized with 0. Otherwise, to initialize it, you can assign it a small number from 0 to 255. To convert a value to a Byte value, you can use CByte(). To do this, enter the value or the expression in the parentheses of CByte(). If the conversion is successful, CByte() produces a Byte value. There is no type character for the Byte data type.
A Signed Byte
If you want to use a very small number but it does not have to be positive, the Visual Basic language provides an alternative. A signed byte is a small number that is between -127 and 128. To declare a variable for such a number,
Created by www.ebooktutorials.blogspot.in
you can use the SByte data type. This can be done as follows: Module Exercise Sub Main() Dim Temperature As SByte End Sub End Module To convert a value to an SByte value, use CSByte(). There is no type character for the SByte data type.
A Short Integer
An integer is a natural number larger than the Byte. Examples of such ranges are the number of pages of a book, the age of a person. To declare a variable that can hold natural numbers in the range of -32768 to 32767, you can use the Short data type. Here is an example: Module Exercise Sub Main() Dim MusicTracks As Short End Sub End Module By default, a Short variable is initialized with 0. After declaring a Short variable, you can initialize it with the necessary value that must be a relatively small integer from -32768 to 32767. Here is an example: Module Exercise Sub Main() Dim MusicTracks As Short MusicTracks = 16 MsgBox(MusicTracks) End Sub End Module In some cases, the compiler may allocate more memory than the variable needs, beyond the area required by a Short value. To indicate that the number must be treated as a Short and not another type of value, type s or S on the right of the initializing value. Here is an example: Module Exercise Sub Main() Dim MusicTracks As Short MusicTracks = 16S MsgBox("This album contains " & MusicTracks & " tracks.") End Sub End Module This would produce:
To convert a value to a short integer, you can use CShort() by entering the value or the expression in the parentheses of CShort(). If the conversion is successful, CShort() produces a Short value. There is no type character for the Short data type.
Created by www.ebooktutorials.blogspot.in
that must be positive, you must store it as an unsigned short integer. An unsigned short integer is a natural number between 0 and 65535. To declare a variable that would hold a short positive number, you can use the UShort data type. Here is an example: Module Exercise Sub Main() Dim TotalNumberOfStudents As UShort End Sub End Module There is no type character for the UShort data type. To convert something to an unsigned short integer, put in the parentheses of CUShort().
An Integer
If you want a variable to hold values larger than the Short data type can accommodate, you can use the Integer data type to declare it. A variable declared with the Integer data type can hold a value between -2,147,483,648 and 2,147,483,647. Here is an example: Module Exercise Sub Main() Dim NumberOfPages As Integer End Sub
Created by www.ebooktutorials.blogspot.in
End Module Alternatively, you can use the % type character to declare an integral variable. Here is an example: Module Exercise Sub Main() Dim NumberOfPages% End Sub End Module To convert a value to an integer, use CInt(): enter the value or the expression in the parentheses of CInt(). If the conversion is successful, CInt() produces an integral value. After declaring an Integer variable, the compiler initializes it with a 0 value. Still, you can initialize it with the necessary value but you have three or four alternatives. To initialize the variable with a regular natural number, you can simply assign it that number. Here is an example: Module Exercise Sub Main() Dim NumberOfPages As Integer NumberOfPages = 846 MsgBox("This book contains " & NumberOfPages & " pages.") End Sub End Module This would produce:
The Visual Basic language considers three types of integer values. Instead of just assigning a regular natural number, to indicate that the value must be considered as an integer, you can enter i or I on the right side of the value. Here is an example: Module Exercise Sub Main() Dim NumberOfPages As Integer NumberOfPages = 846I End Sub End Module The second type of integral number is referred to as hexadecimal. On a surface, it is primarily a different way of representing a number by using a combination of 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f, A, B, C, D, E, or F. This still allows you to represent any natural number. To initialize an integer variable with a hexadecimal number, start the value with &h or &H. Here is an example: Module Exercise Sub Main() Dim NumberOfStudents As Integer NumberOfStudents = &H4A26EE MsgBox("School Current Enrollment: " & NumberOfStudents & " students.") End Sub End Module This would produce:
Created by www.ebooktutorials.blogspot.in
Besides the regular natural or the hexadecimal numbers, the third type of value an Integer variable can hold is referred to as octal. This is a technique used to represent a natural number using a combination of 0, 1, 2, 3, 4, 5, 6, and 7. To use such a value, start it with &o or &O (the letter O and not the digit 0). Here is an example: Module Exercise Sub Main() Dim NumberOfStudents As Integer NumberOfStudents = &O4260 MsgBox("School Current Enrollment: " & NumberOfStudents & " students.") End Sub End Module This would produce:
An Unsigned Integer
We saw that the Integer data type is used to declare a variable for a large number that can be negative or positive. If you want the number to only be positive, you can declare it as an unsigned integer. An unsigned integer is a number between 0 and 4294967295. Examples are the population of a city, the distance between places of different countries, the number of words of a book. To declare a variable that can a large positive number, use the UInteger data type. Here is an example: Module Exercise Sub Main() Dim Population As UInteger End Sub End Module You can initialize the variable using a positive integer in decimal, hexadecimal, or octal format. To convert a value to an unsigned short integer, use CUInt() by entering the value or the expression in the parentheses. There is no type character for the UInteger data type.
A Long Integer
A long integer is a very large natural number that is between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807. To declare a variable that can hold a very large natural number, use the Long data type. Here is an example: Module Exercise Sub Main() Dim Population As Long End Sub End Module Instead of the AS Long expression, as an alternatively, you can also use the @ symbol as the type character to declare a Long variable. Here is an example: Module Exercise Sub Main() Dim Population@ End Sub End Module To convert a value to a long integer, you can use CLng(). To do this, enter the value or the expression in the
Created by www.ebooktutorials.blogspot.in
parentheses of CLng(). If the conversion is successful, CLng() produces a Long integer value. Like all integers, a Long variable is initialized, by default, with 0. After declaring a Long variable, you can initialize with the necessary natural number. Here is an example: Module Exercise Sub Main() Dim Population@ Population@ = 9793759 MsgBox("Country Population: " & Population) End Sub End Module This would produce:
To indicate that the value must be treated as Long, type l or L on the right side of the number. Here is an example: Module Exercise Sub Main() Dim Population@ Population@ = 9793759L End Sub End Module Because Long is primarily an integral like the Integer data type we reviewed earlier, you can also initialize it using a decimal, a hexadecimal, or an octal value. Here is an example of a variable initialized with a hexadecimal value: Module Exercise Sub Main() Dim Population@ Population = &HFF42AD MsgBox("Country Population: " & Population) End Sub End Module This would produce:
Created by www.ebooktutorials.blogspot.in
There is no type character for the ULong data type. To convert a value to an unsigned long integer, use CULng().
Floating-Point Numbers
Introduction
A real number is one that displays a decimal part. This means that the number can be made of two sections separated by a symbol that is referred to as the Decimal Separator or Decimal Symbol. This symbol is different by language, country, group of languages, or group of countries. In US English, this symbol is the period as can be verified from the Regional (and Language) Settings of the Control Panel of computers of most regular users:
On both sides of the Decimal Symbol, digits are used to specify the value of the number. The number of digits on the right side of the symbol determines how much precision the number offers.
Single-Precision
A decimal number is said to have single precision if it can include a decimal part but the precision of the number is not important. In the Visual Basic language, such a number has a value that can range from -3.402823e 38 and -1.401298e 45 if the number is negative, or 1.401298e -45 and 3.402823e 38 if the number is positive. To declare a variable that can hold small decimal numbers with no concern for precision, use the Single data type. Here is an example:
Created by www.ebooktutorials.blogspot.in
Module Exercise Sub Main() Dim Distance As Single End Sub End Module Instead of the AS Single expression, you can use the ! symbol as the type character. Here is an example: Module Exercise Sub Main() Dim Distance! End Sub End Module The ! symbol can also be used in other scenarios in the Visual Basic language. Whenever you use it, make sure the word that comes to its right is not the name of a variable. A Single variable is initialized with 0. After declaring a Single variable, you can declare it with the necessary value. Here is an example: Module Exercise Sub Main() Dim Distance! Distance! = 195.408 MsgBox("Distance: " & Distance) End Sub End Module This would produce:
In some cases, the compiler may allocate more memory than necessary for the variable. For example, the above value is more suitable for another type as we will see in the next section. Otherwise, to indicate that the variable must be treated as a decimal number with single-precision, type f or F on the right side of the number. Here is an example: Module Exercise Sub Main() Dim Distance! Distance! = 195.408f End Sub End Module To convert a string to a long integer, call CSng(). Enter the value or the expression in the parentheses of CSng(). If the conversion is successful, CSng() produces a Single value.
Double-Precision
While the Single data type can allow large numbers, it offers less precision. For an even larger number, Visual Basic provides the Double data type. This is used for a variable that would hold numbers that range from 1.79769313486231e 308 to 4.94065645841247e 324 if the number is negative or from 1.79769313486231E308 to 4.94065645841247E324 if the number is positive. To declare a variable that can store large decimal numbers with a good level of precision, use the Double keyword. In most circumstances, it is preferable to use Double instead of Single when declaring a variable that would hold a decimal number. Although the Double takes more memory spaces (computer memory is not expensive anymore(!)), it provides more precision.
Created by www.ebooktutorials.blogspot.in
Here is an example of declaring a Double variable: Module Exercise Sub Main() Dim TempFactor As Double End Sub End Module If you want, you can omit the AS Double expression but use the # symbol instead to declare a Double variable. This can be done as follows: Module Exercise Sub Main() Dim TempFactor# End Sub End Module A double-precision variable is initialized with a 0 value. After declaring a Double variable, you can initialize it with the needed value. Here is an example: Module Exercise Sub Main() Dim TempFactor# TempFactor# = 482 MsgBox("Temperature: " & TempFactor & " Degrees") End Sub End Module This would produce:
To indicate that the variable being used must be treated with double precision, enter r or R on its right side. Here is an example: Module Exercise Sub Main() Dim TempFactor# TempFactor# = 482r MsgBox("Temperature: " & TempFactor & " Degrees") End Sub End Module To convert a value to a double-precision number, call CDbl() by entering the value or the expression in the parentheses of CDbl(). If CDbl() succeeds, it produces a Double value.
Created by www.ebooktutorials.blogspot.in
strDeposit = InputBox("Enter Initial Deposit:") strWithdrawals = InputBox("Enter total withdrawals:") InitialDeposit = CDbl(strDeposit) Withdrawals = CDbl(strWithdrawals) CurrentBalance = InitialDeposit - Withdrawals Result = " =-= Yugo National Bank =-=" & vbCrLf & "Customer Name: " & vbTab & CustomerName & vbCrLf & "Account Number: " & vbTab & AccountNumber & vbCrLf & "Deposits: " & vbTab & InitialDeposit & vbCrLf & "Withdrawals: " & vbTab & Withdrawals & vbCrLf & "Current Balance: " & vbTab & CurrentBalance MsgBox(Result) End Sub End Module 2. To execute the program, press F5 3. Enter the requested values. Here are examples:
Created by www.ebooktutorials.blogspot.in
Decimal
The decimal data type can be used to declare a variable that would hold significantly large values that can be stored in a combination of 128 bits. You declare such a variable using the Decimal keyword. The values stored in a decimal variable can range from 1.0 x 1028 to 7.9 x 10 28 with a precision of 28 to 29 digits. Because of this high level of precision, the Decimal data type is suitable for currency values. Like those of the other numeric types, by default, a variable declared as Decimal is initialized with 0. After declaring a decimal variable, you can initialize it with a natural number. To indicate to the compiler to reserve space enough to store a decimal value, add a d or D to the right side of the value. Here is an example: Module Exercise Sub Main() Dim DistanceBetweenPlanets As Decimal DistanceBetweenPlanets = 592759797549D End Sub End Module To convert a value or an expression to Decimal, you can call CDec().
Created by www.ebooktutorials.blogspot.in
Sub Main() Dim Letter As Char Letter = "W"c End Sub End Module To convert a value to Char, you can call CChar().
Strings
A string is an empty text, a letter, a word or a group of words considered "as is". To declare a string variable, you can use the String data type. Here is an example: Module Exercise Sub Main() Dim Sentence As String End Sub End Module If you want, you can replace the AS String expression with the $ symbol when declaring a string variable. This can be done as follows: Module Exercise Sub Main() Dim Sentence$ End Sub End Module After declaring a String variable, by default, the compiler initializes it with an empty string. Otherwise, you can initialize it with a string of your choice. To do this, include the string between double quotes. Here is an example: Module Exercise Sub Main() Dim Sentence$ Sentence$ = "He called me" End Sub End Module If you want to include a double-quote character in the string, you can double it. Here is an example: Module Exercise Sub Main() Dim Sentence$ Sentence$ = "Then she said, ""I don't love you no more."" and I left" MsgBox(Sentence) End Sub End Module This would produce:
To convert a value to a string, call CStr() and enter the value or the expression in its parentheses. If the value is an appropriate date or time, CStr() would produces a string that represents that date or that time value.
Created by www.ebooktutorials.blogspot.in
1. Continue with the YugoNationalBank1 application. To use a few string variables, change the program as follows: Module YugoNationalBank Sub Main() Dim CustomerName As String Dim AccountNumber As String Dim InitialDeposit As Double Dim Withdrawals As Double Dim CurrentBalance As Double Dim Result As String Dim strDeposit As String, strWithdrawals As String CustomerName = InputBox("Enter Customer Name:") AccountNumber = InputBox("Enter Account #:") strDeposit = InputBox("Enter Initial Deposit:") strWithdrawals = InputBox("Enter total withdrawals:") InitialDeposit = CDbl(strDeposit) Withdrawals = CDbl(strWithdrawals) CurrentBalance = InitialDeposit - Withdrawals Result = " =-= Yugo National Bank =-=" & vbCrLf & "Customer Name: " & vbTab & CustomerName & vbCrLf & "Account Number: " & vbTab & AccountNumber & vbCrLf & "Deposits: " & vbTab & InitialDeposit & vbCrLf & "Withdrawals: " & vbTab & Withdrawals & vbCrLf & "Current Balance: " & vbTab & CurrentBalance MsgBox(Result) End Sub End Module 2. To execute the application, press F5 3. Provide the requested values. Here is an example:
Created by www.ebooktutorials.blogspot.in
The rules for the time values are defined in the Time property page:
When using date and time values in your applications, you should not change these rules because the application will refer to them when it is installed in someone else's computer.
Created by www.ebooktutorials.blogspot.in
By default, a Date variable is initialized with January 1st, 0001 at midnight as the starting value. After declaring a Date variable, you can initialize it with an appropriate date or time or date and time value. The value can be included in double-quotes. Here is an example: Module Exercise Sub Main() Dim DateOfBirth As Date DateOfBirth = "08/14/1982" MsgBox("Date of Birth: " & DateOfBirth) End Sub End Module This would produce:
If you intend to use only a date value for a Date variable, its corresponding time part would be set to midnight of the same date. Based on this, the above program would produce: 8/14/1982 12:00:00 AM If you intend to use only a time value for your Date variable, the date part of the variable would be set to January 1st, 0001. A Date value can also be included between two # signs. Here is an example: Module Exercise Sub Main() Dim DateOfBirth As Date Dim KickOffTime As Date DateOfBirth = "08/14/1982" KickOffTime = #6:45:00 PM# MsgBox("Date of Birth: " & DateOfBirth) MsgBox("Kick off Time: " & KickOffTime) End Sub End Module To convert a value to a date or a time value, write an appropriate date or a recognizable time in the parentheses of CDate(). If the value is appropriate, CDate() produces a Date value.
Created by www.ebooktutorials.blogspot.in
NumberOfShirts = InputBox("Enter Number of Shirts") NumberOfPants = InputBox("Enter Number of Pants") NumberOfOtherItems = InputBox("Enter Number of Other Items") ' Perform the necessary calculations SubTotalShirts = NumberOfShirts * 1.15 SubTotalPants = NumberOfPants * 1.95 SubTotalOtherItems = NumberOfOtherItems * 3.25 ' Calculate the "temporary" total of the order TotalOrder = SubTotalShirts + SubTotalPants + SubTotalOtherItems ' Calculate the tax amount using a constant rate TaxAmount = TotalOrder * 0.0575 ' Add the tax amount to the total order NetTotal = TotalOrder + TaxAmount ' Communicate the total to the user... MsgBox("The Total order is: " & NetTotal) ' and request money for the order AmountTended = InputBox("Amount Tended?") MsgBox(vbTab & "-/- Georgetown Dry Cleaner -/-" & vbCrLf & "==============================" & vbCrLf & vbTab & "Customer Name: " & CustomerName & vbCrLf & vbTab & "Customer Phone: " & CustomerPhone & vbCrLf & vbTab & "Order Date: " & OrderDate & vbCrLf & vbTab & "Order Time: " & OrderTime & vbCrLf & "------------------------------------------------------------" & vbCrLf & "Item Type" & vbTab & "Qty" & vbTab & "Unit/Price" & vbTab & "Sub-Total" & vbCrLf & "------------------------------------------------------------" & vbCrLf & "Shirts " & vbTab & vbTab & CStr(NumberOfShirts) & vbTab & "1.15" & vbTab & CStr(SubTotalShirts) & vbCrLf & "Pants " & vbTab & vbTab & CStr(NumberOfPants) & vbTab & "1.95" & vbTab & CStr(SubTotalPants) & vbCrLf & "Other Items " & vbTab & CStr(NumberOfOtherItems) & vbTab & "3.25" & vbTab & CStr(SubTotalOtherItems) & vbCrLf & "-----------------------------------------------------------" & vbCrLf & vbTab & "Total Cleaning: " & vbTab & CStr(TotalOrder) & vbCrLf & vbTab & "Tax Rate: " & vbTab & "5.75%" & vbCrLf & vbTab & "Tax Amount: " & vbTab & CStr(TaxAmount) & vbCrLf & vbTab & "Net Price: " & vbTab & CStr(NetTotal) & vbCrLf & "==============================") End Sub End Module 3. To execute the program, on the main menu, click Debug -> Start Debugging 4. Enter the number of shirts as 6, the number of pants as 4, and the number of other items as 2
Created by www.ebooktutorials.blogspot.in
Object
An Object can be any type of data that you want to use in your program. In most cases, but sparingly, it can be used to declare a variable of any type. Here are examples: Module Exercise Sub Main() Dim CountryName As Object Dim NumberOfPages As Object Dim UnitPrice As Object CountryName = "Australia" NumberOfPages = 744 UnitPrice = 248.95 MsgBox("Country Name: " & CountryName) MsgBox("Number of Pages: " & NumberOfPages) MsgBox("Unit Price: " & UnitPrice) End Sub End Module If you do not specify a data type or cannot figure out what data type you want to use, you can use the Object data type. As you can see from the result of the above program, the vbc compiler knows how to convert the value of any Object variable to the appropriate type. On the other hand, to convert a value or an expression to the Object type, you can use CObj().
Previous
Next
Created by www.ebooktutorials.blogspot.in
Using Variables
Constants
Introduction
A constant is a value that doesn't change. There are two types of constants you will use in your programs: those supplied to you and those you define yourself. To create a constant to use in your program type the Const keyword followed by a name for the variable, followed by the assignment operator "=", and followed by the value that the constant will hold. Here is an example:
Module Exercise Sub Main() Const DateOfBirth = #12/5/1974# MsgBox(DateOfBirth) End Sub End Module When defining a constant like this, the compiler would know the type of data to apply to the variable. In this case the DateOfBirth constant holds a Date value. Still, to be more explicit, you can indicate the type of value of the constant by following its name with the As keyword and the desired data type. Based on this, the above program would be: Module Exercise Sub Main() Const DateOfBirth As Date = #12/5/1974# MsgBox("Date of Birth: " & DateOfBirth) End Sub End Module When creating a constant, if its value supports a type character, instead of using the As keyword, you can use that type character. Here is an example: Module Exercise Sub Main() Const Temperature% = 52 End Sub End Module As mentioned earlier, the second category of constants are those that are built in the Visual Basic language. Because there are many of them and used in different circumstances, when we need one, we will introduce and then use it.
Created by www.ebooktutorials.blogspot.in
Sub Main() Const UnitPriceShirts As Double = 1.25 Const UnitPricePants As Double = 1.95 Const UnitPriceOtherItems As Double = 3.25 Const TaxRate As Double = 5.75 Dim CustomerName As String, CustomerPhone As String Dim OrderDate As Date, OrderTime As Date ' Unsigned numbers to represent cleaning items Dim NumberOfShirts As UInteger, NumberOfPants As UInteger Dim NumberOfOtherItems As UInteger ' Each of these sub totals will be used for cleaning items Dim SubTotalShirts As Double, SubTotalPants As Double Dim SubTotalOtherItems As Double ' Values used to process an order Dim TotalOrder As Double, TaxAmount As Double Dim NetTotal As Double Dim AmountTended As Double ' Request order information from the user CustomerName = InputBox("Enter Customer Name:") CustomerPhone = InputBox("Enter Customer Phone:") OrderDate = InputBox("Enter the order date:") OrderTime = InputBox("Enter the order time:") NumberOfShirts = InputBox("Enter Number of Shirts") NumberOfPants = InputBox("Enter Number of Pants") NumberOfOtherItems = InputBox("Enter Number of Other Items") ' Perform the necessary calculations SubTotalShirts = NumberOfShirts * UnitPriceShirts SubTotalPants = NumberOfPants * UnitPricePants SubTotalOtherItems = NumberOfOtherItems * UnitPriceOtherItems ' Calculate the "temporary" total of the order TotalOrder = SubTotalShirts + SubTotalPants + SubTotalOtherItems ' Calculate the tax amount using a constant rate TaxAmount = TotalOrder * TaxRate / 100 ' Add the tax amount to the total order NetTotal = TotalOrder + TaxAmount ' Communicate the total to the user... MsgBox("The Total order is: " & NetTotal) ' and request money for the order AmountTended = InputBox("Amount Tended?") MsgBox(vbTab & "-/- Georgetown Dry Cleaner -/-" & vbCrLf & "==============================" & vbCrLf & vbTab & "Customer Name: " & CustomerName & vbCrLf & vbTab & "Customer Phone: " & CustomerPhone & vbCrLf & vbTab & "Order Date: " & OrderDate & vbCrLf & vbTab & "Order Time: " & OrderTime & vbCrLf & "------------------------------------------------------------" & vbCrLf & "Item Type" & vbTab & "Qty" & vbTab & "Unit/Price" & vbTab & "Sub-Total" & vbCrLf & "------------------------------------------------------------" & vbCrLf & "Shirts " & vbTab & vbTab & CStr(NumberOfShirts) & vbTab & CStr(UnitPriceShirts) & vbTab & CStr(SubTotalShirts) & vbCrLf & "Pants " & vbTab & vbTab & CStr(NumberOfPants) & vbTab & CStr(UnitPricePants) & vbTab & CStr(SubTotalPants) & vbCrLf & "Other Items " & vbTab & CStr(NumberOfOtherItems) & vbTab & CStr(UnitPriceOtherItems) & vbTab & CStr(SubTotalOtherItems) & vbCrLf & "-----------------------------------------------------------" & vbCrLf & vbTab & "Total Cleaning: " & vbTab & CStr(TotalOrder) & vbCrLf & vbTab & "Tax Rate: " & vbTab & CStr(TaxRate) & "%" & vbCrLf & vbTab & "Tax Amount: " & vbTab & CStr(TaxAmount) & vbCrLf & vbTab & "Net Price: " & vbTab & CStr(NetTotal) & vbCrLf & "==============================") End Sub End Module 9. On the main menu, click Project -> GeorgetownDryCleaningServices2 Properties 10. Click the arrow of the Application Type box and select Windows Forms Application 11. Click the Close button 13. Enter values as follows: Customer Name: Jeannette Sharma to close the Property Pages window
12. To execute the program, on the main menu, click Debug -> Start Debugging
Created by www.ebooktutorials.blogspot.in
Customer Phone: Order Date: Order Time Number of Shirts: Number of Pants: (301) 218-9000 04/11/2008 08:24 6 4
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.
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.
Sub Main() Dim CustomerName As String, CustomerPhone As String . . . No Change End Sub End Module 2. To execute the program, press F5 3. Enter values as follows: Customer Name: Customer Phone: Order Date: Order Time Number of Shirts: Number of Pants: Shawn Nitty (301) 423-7744 04/11/2008 09:12 0 2
Number of Other Items: 0 4. Enter the amount tended as 20 5. Close the message box and return to your programming environment
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
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
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.
File 2: Exercise.vb Module Exercise Sub Main() FullName = "Gertrude Monay" MsgBox("Full Name: " & FullName) End Sub End Module
Created by www.ebooktutorials.blogspot.in
End Module This would produce:
Private CustomerName As String, CustomerPhone As String Private OrderDate As Date, OrderTime As Date ' Unsigned numbers to represent cleaning items Private NumberOfShirts As UInteger, NumberOfPants As UInteger Private NumberOfOtherItems As UInteger ' Each of these sub totals will be used for cleaning items Private SubTotalShirts As Double, SubTotalPants As Double Private SubTotalOtherItems As Double ' Values used to process an order Private TotalOrder As Double, TaxAmount As Double Private NetTotal As Double Private AmountTended As Double Sub Main() ' Request order information from the user CustomerName = InputBox("Enter Customer Name:") . . . No Change End Sub End Module 2. To execute the program, on the Standard toolbar, click the Start Debugging button 3. Enter values as follows: Customer Name: Customer Phone: Order Date: Order Time Number of Shirts: Number of Pants: Landry Kurtzmann (202) 223-3325 04/12/2008 07:35 8 2
Number of Other Items: 0 4. Enter the amount tended as 50 5. Close the message box and return to your programming environment
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:
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)
Created by www.ebooktutorials.blogspot.in
3. Enter values as follows: Customer Name: Customer Phone: Order Date: Order Time Number of Shirts: Number of Pants: William Nessif (301) 220-3737 04/12/2008 08:26 3 3
Number of Other Items: 3 4. Enter the amount tended as 40 5. Close the message box and return to your programming environment
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
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.
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:
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:
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:
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.
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:
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.
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.
Created by www.ebooktutorials.blogspot.in
Previous Copyright 2008-2010 FunctionX 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: Return 0 End Function End Module Here is an example of running the program: " & TypeOfHouse & vbCrLf & " & TypeOfGarage)
For such a program, the numbers can be vague. 1 can be considered a general number but, in our program, it can represent a Single Family house or an Interior type of garage. At the same time,
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
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
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
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
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:
Created by www.ebooktutorials.blogspot.in
Home
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
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:
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:
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.
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.
Created by www.ebooktutorials.blogspot.in
End Module This would produce:
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.
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.
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:
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:
The CStr() function is used to convert any type of value to a string. If the value to be converted is a number, you can use the Str() function. Its syntax is: Public Shared Function Str(ByVal Number As Object) As String This function expects a number as argument. Here is an example: Public Module Exercise Public Function Main() As Integer Dim Number As Double Number = 1450.5 / 2 MsgBox("1450.50 / 2 = Return 0 End Function End Module This would produce: " & Str(Number))
Created by www.ebooktutorials.blogspot.in
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
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.
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:
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
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:
Because the StrReverse() function returns a string, you can write it as StrReverse$.
Strings and Empty Spaces
The simplest string is probably one that you declared and initialized. In some other cases, you may
Created by www.ebooktutorials.blogspot.in
work with a string that you must first examine. For example, for some reason, a string may contain an empty space to its left or to its right. If you simply start performing a certain operation on it, the operation may fail. One of the first actions you can take on a string would consist of deleting the empty space(s), if any on its sides. To remove all empty spaces from the left side of a string, you can call the LTrim() function. Its syntax is: Public Shared Function LTrim(ByVal str As String) As String To remove all empty spaces from the right side of a string, you can call the RTrim() function. Its syntax is: Public Shared Function RTrim(ByVal str As String) As String To remove the empty spaces from both sides of a string, you can call the Trim() function. Its syntax is: Public Shared Function Trim(ByVal str As String) As String
Creating an Empty Spaced String
If you want to create a string made of one or more empty spaces, you can call the Space() function. Its syntax is: Public Shared Function Space(ByVal Number As Integer) As String This function is the programmatic equivalent to pressing the Space bar when typing a string to insert an empty space between two characters.
Strings Comparisons
To compare two strings, you can call the StrCmp() function. Its syntax is: Public Shared Function StrComp( _ ByVal String1 As String, _ ByVal String2 As String, _ <Microsoft.VisualBasic.OptionCompareAttribute> _ Optional ByVal Compare As Microsoft.VisualBasic.CompareMethod _ ) As Integer The first and the second arguments to this function are strings and both are required. After the function has performed the comparison, it returns -1 if string1 is less than string2 0 if string1 and string2 are equal 1 if string1 is greater than string2 The third argument allows you to specify the comparison in binary or text format. This argument can have one of the following values: Constant vbBinaryCompare vbTextCompare Here is an example: Private Dim Dim Dim Sub cmdCreate_Click() strValue1 As String strValue2 As String iComparisonValue Value Description 0 1 Perform a binary comparison Perform a textual comparison
strValue1 = "Rpublique d'Afrique du Sud" strValue2 = "Republic of South Africa" iComparisonValue = StrComp(strValue1, strValue2, vbTextCompare) MsgBox "Comparing """ & strValue1 & """ with """ & _ strValue2 & """ produces " & CStr(iComparisonValue) End Sub This would produce:
Created by www.ebooktutorials.blogspot.in
Home
Created by www.ebooktutorials.blogspot.in
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
Created by www.ebooktutorials.blogspot.in
MsgBox(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
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
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
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
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
4. Click OK to close the message box and return to your programming environment
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
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
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".
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:
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
"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
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.
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.
End Module
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.
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
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.
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
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
Next
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 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
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.
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
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:
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
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.
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
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
12. Close the DOS window and return to your programming environment
Home
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 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
_ | 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
Home
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
Conversion Functions
You may recall that when studying data types, we saw that each had a corresponding function used to convert a string value or an expression to that type. As a reminder, the general syntax of the conversion functions is: ReturnType = FunctionName(Expression) The Expression could be of any kind. For example, it could be a string or expression that would produce a value such as the result of a calculation. The conversion function would take such a value, string, or expression and attempt to convert it. If the conversion is successful, the function would return a new value that is of the type specified by the ReturnType in our syntax. The conversion functions are as follows: Function Name CBool CByte CDbl CDec CInt CLng CObj CSByte CShort CSng CUInt CULng CUShort Return Type Boolean Byte Double Decimal Integer Long Object SByte Short Single UInt ULong UShort Description Converts an expression into a Boolean value Converts an expression into Byte number Converts an expression into a floating-point number with double precision Converts an expression into a decimal number Converts an expression into an integer (natural) number Converts an expression into a long integer (a large natural) number Converts an expression into an Object type Converts an expression into a signed byte Converts an expression into a short integer Converts an expression into a floating-point number with single precision Converts an expression into an unsigned integer Converts an expression into an unsigned long integer Converts an expression into an unsigned short integer
These functions allow you to convert a known value to a another type. Besides these functions, the Visual Basic language provides a function named CType. Its syntax is: CType(expression, typename) As you can see, the CType() function takes two arguments. The first argument is the expression or the value that you want to convert. An example could be name of a variable or a calculation: CType(250.48 * 14.05, ...)
The second argument is the type of value you want to convert the first argument to. From what have learned so far, this second argument can be one of the data types we reviewed in Lesson 3. Here is an example: CType(250.48 * 14.05, Single) If you choose one of the Visual Basic language's data types, the expression produced by the first argument must be able to produce a value that is conform to the type of the second argument: The conversion from the first argument to the type of the second argument must be possible: the value produced by the first must be convertible to the second arguments. For example, if the first argument is a calculation, the second argument must be a number-based data type. In the same way, you cannot convert a date to a number-based type If the first argument is a number or the result of a calculation, its resulting value must be lower than or up to the range of values of the second argument. Here is an example:
Public Module Exercise Public Function Main() As Integer MsgBox(CType(250.48 * 14.05, Single)) Return 0 End Function End Module
This would produce:
If the first argument is a number or the result of a calculation that produces an integer or a floating-point number, its resulting value must be convertible to an integer or a floating point number up to the range of values of the second argument. Here is an example:
Public Module Exercise Public Function Main() As Integer MsgBox(CType(7942.225 * 202.46, UInteger)) Return 0 End Function End Module
This would produce:
If the first argument is a number or the result of a calculation that produces an integer or a floating-point number, the second argument is a number-based data type but whose range cannot hold the resulting value of the first argument, the conversion would not be allowed (the conversion will fail):
After the CType() function has performed its conversion, it returns a value that is the same category as the second argument. For example, you can call a CType() function that converts an expression to a long integer. Here is an example: Public Module Exercise Public Function Main() As Integer Dim Number As Long Number = CType(7942.225 * 202.46, Long) Return 0 End Function End Module The function can also return a different type, as long as its type can hold the value produced by the expression. Here are two examples: Public Module Exercise Public Function Main() As Integer Dim Number As UInteger Number = CType(7942.225 * 202.46, Long) Return 0 End Function End Module Or Public Module Exercise Public Function Main() As Integer Dim Number As Single Number = CType(7942.225 * 202.46, Long) Return 0 End Function End Module If you try storing the returned value into a variable that cannot hold it, you would receive an error:
Home
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
Home
Home
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
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
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.
Home
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:
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:
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:
Home
7. Close the message box and the DOS window to return to your programming environment
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
4. Close the message box and the DOS window then return to your programming environment
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.
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
HourlySalaryFormatter = "0.00" WeeklyHoursFormatter = "0.00" EmployeeName = InputBox("Enter Employee Name:", "Bethesda Car Rental", "John Doe") StrHourlySalary = InputBox("Enter Employee Hourly Salary:", "Bethesda Car Rental", "0.00") If IsNumeric(StrHourlySalary) Then HourlySalaryFormatter = FormatCurrency(CDbl(StrHourlySalary)) Else MsgBox("The number " & StrHourlySalary & " you entered " & "for the hourly salary is not valid", MsgBoxStyle.Exclamation Or MsgBoxStyle.Critical, "Bethesda Car Rental") End If StrWeeklyHours = InputBox("Enter Employee Weekly Hours:", "Bethesda Car Rental", "0.00") If IsNumeric(StrWeeklyHours) Then WeeklyHoursFormatter = FormatNumber(CDbl(StrWeeklyHours)) Else MsgBox("The value " & StrWeeklyHours & " you provided " & "for the weekly hours is not valid", MsgBoxStyle.Exclamation Or MsgBoxStyle.Critical, "Bethesda Car Rental") End If Payroll = "======================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Employee Payroll =-=-==" & vbCrLf & "-------------------------------------------" & vbCrLf & "Employee Name:" & vbTab & EmployeeName & vbCrLf & "Hourly Salary:" & vbTab & HourlySalaryFormatter & vbCrLf & "Weekly Hours:" & vbTab & WeeklyHoursFormatter & vbCrLf & "======================" MsgBox(Payroll, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") Return 0 End Function End Module 2. Execute the application 3. Enter the Employee name as Helene Mukoko, the hourly salary as 2W.o5, and the weekly hours as Thirty Eight 4. Close the message box and the DOS window then return to your programming environment 5. To calculate the employee's pay, change the document as follows: Module BethesdaCarRental Public Function Main() As Integer Dim EmployeeName As String Dim StrHourlySalary As String, StrWeeklyHours As String Dim HourlySalary As Double Dim WeeklyHours As Double Dim RegularTime As Double, Overtime As Double Dim RegularPay As Double, OvertimePay As Double Dim NetPay As Double Dim Payroll As String HourlySalary = "0.00" WeeklyHours = "0.00" EmployeeName = InputBox("Enter Employee Name:", "Bethesda Car Rental", "John Doe") StrHourlySalary = InputBox("Enter Employee Hourly Salary:", "Bethesda Car Rental", "0.00") If IsNumeric(StrHourlySalary) Then HourlySalary = CDbl(StrHourlySalary) Else MsgBox("The number " & StrHourlySalary & " you entered " & "for the hourly salary is not valid", MsgBoxStyle.Exclamation Or MsgBoxStyle.Critical, "Bethesda Car Rental") End If StrWeeklyHours = InputBox("Enter Employee Weekly Hours:", "Bethesda Car Rental", "0.00") If IsNumeric(StrWeeklyHours) Then WeeklyHours = CDbl(StrWeeklyHours) Else MsgBox("The value " & StrWeeklyHours & " you provided " & "for the weekly hours is not valid", MsgBoxStyle.Exclamation Or MsgBoxStyle.Critical, "Bethesda Car Rental") End If If WeeklyHours < 40 Then RegularTime = WeeklyHours
Overtime = 0 RegularPay = HourlySalary * RegularTime OvertimePay = 0 NetPay = RegularPay Else RegularTime = 40 Overtime = WeeklyHours - 40 RegularPay = HourlySalary * 40 OvertimePay = HourlySalary * Overtime NetPay = RegularPay + OvertimePay End If Payroll = "======================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Employee Payroll =-=-==" & vbCrLf & "-------------------------------------------" & vbCrLf & "Employee Name:" & vbTab & EmployeeName & vbCrLf & "Hourly Salary:" & vbTab & FormatCurrency(HourlySalary) & vbCrLf & "Weekly Hours:" & vbTab & FormatNumber(WeeklyHours) & vbCrLf & "Regular Pay:" & vbTab & FormatCurrency(RegularPay) & vbCrLf & "Overtime Pay:" & vbTab & FormatCurrency(OvertimePay) & vbCrLf & "Total Pay:" & vbTab & FormatCurrency(NetPay) & vbCrLf & "======================" MsgBox(Payroll, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") Return 0 End Function End Module 6. Execute the application 7. Enter the Employee name as Helene Mukoko, the hourly salary as 22.35, and the weekly hours as 42.50
8. Close the message box and the DOS window then return to your programming environment
Dim MemberAge As Int16 Dim MemberCategory As String MemberAge = 16 MemberCategory = IIf(MemberAge <= 18, "Teen", "Adult") MsgBox("Membership: " & MemberCategory) Return 0 End Function End Module This would produce the same result we saw earlier.
MsgBox(Payroll, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") Return 0 End Function End Module 2. Execute the application 3. Enter the Employee name as Raymond Kouma, the gender as 2, hourly salary as 28.25, and the weekly hours as 44.50
4. Close the message box and the DOS window then return to your programming environment 5. Create a new Console Application named BCR2 6. In the Solution Explorer, right-click Module1.vb and click Rename 7. Type BethesdaCarRental.vb and press Enter 8. Accept to change the file name and change the document as follows: Module BethesdaCarRental Public Function Main() As Integer Dim CustomerName As String Dim RentStartDate As Date, RentEndDate As Date Dim NumberOfDays As Integer Dim RateType As String, RateApplied As Double Dim OrderTotal As Double Dim OrderInvoice As String RateType = "Weekly Rate" RateApplied = 0 OrderTotal = RateApplied CustomerName = InputBox("Enter Customer Name:", _ "Bethesda Car Rental", "John Doe") RentStartDate = CDate(InputBox("Enter Rent Start Date:", _ "Bethesda Car Rental", #1/1/1900#)) RentEndDate = CDate(InputBox("Enter Rend End Date:", _ "Bethesda Car Rental", #1/1/1900#)) NumberOfDays = DateDiff(DateInterval.Day, RentStartDate, RentEndDate) RateApplied = CDbl(InputBox("Enter Rate Applied:", "Bethesda Car Rental", 0)) OrderInvoice = "===========================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Order Processing =-=-==" & vbCrLf & "------------------------------------------------" & vbCrLf "Processed for:" & vbTab & CustomerName & vbCrLf & "------------------------------------------------" & vbCrLf "Start Date:" & vbTab & RentStartDate & vbCrLf & "End Date:" & vbTab & RentEndDate & vbCrLf & "Nbr of Days:" & vbTab & NumberOfDays & vbCrLf & "------------------------------------------------" & vbCrLf "Rate Type:" & vbTab & RateType & vbCrLf & "Rate Applied:" & vbTab & RateApplied & vbCrLf & "Order Total:" & vbTab & FormatCurrency(OrderTotal) & vbCrLf "===========================" MsgBox(OrderInvoice, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") Return 0 End Function End Module 9. Execute the application 10. Enter the customer name as James Wiley, the start date as 11/07/2008, the end date as 11/10/2008, and the rate applied 49.95
& &
& &
11. Close the message box and the DOS window to return to your programming environment
Notice that the function returns nothing (an empty string). To use this function as an alternative to the If...Then...Else operation, you can pass two values for the second argument. The second argument is actually passed as a list of values. Each value has a specific position as its index. To use the function in an If...Then...Else implementation, pass two values for the second argument. Here is an example: Choose(Status, "Full Time", "Part Time") The second argument to the function, which is the first value of the Choose argument, has an index of 1. The third argument to the function, which is the second value of the Choose argument, has an index of 2. When the Choose() function is called, if the first argument has a value of 1, then the second argument is validated. If the first argument has a value of 2, then the third argument is validated. As mentioned already, you can retrieve the returned value of the function and use it however you want. Here is an example: Module Exercise Public Function Main() As Integer Dim Status As UShort, EmploymentStatus As String Status = 2 EmploymentStatus = Choose(Status, "Full Time", "Part Time") MsgBox("Employment Status: " & EmploymentStatus) Return 0 End Function End Module This would produce:
Home
Next
Functional Conditions
Alternatives to a Condition Being True/False?
The If...Then...ElseIf Condition
The If...Then...ElseIf statement acts like the If...Then...Else expression, except that it offers as many choices as necessary. The formula is: If Condition1 Then Statement1 ElseIf Condition2 Then Statement2 ElseIf Conditionk Then Statementk End If The program will first examine Condition1. If Condition1 is true, the program will execute Statment1 and stop examining conditions. If Condition1 is false, the program will examine Condition2 and act accordingly. Whenever a condition is false, the program will continue examining the conditions until it finds one that is true. Once a true condition has been found and its statement executed, the program will terminate the conditional examination at End If. Here is an example: Module Exercise Public Function Main() As Integer Dim MemberAge As Short MemberAge = 32 If MemberAge <= 18 Then MsgBox("Membership: " & "Teen") ElseIf MemberAge < 55 Then MsgBox("Membership: " & "Adult") End If Return 0 End Function End Module This would produce:
Else MsgBox("Membership: " & "Senior") End If Return 0 End Function End Module This would produce:
& &
& &
6. Execute the application 7. Enter the employee number as 54080, the customer name as James Wiley, the start date as 11/05/2008, the end date as 11/15/2008, and the rate applied 49.95
8. Close the message box and the DOS window to return to your programming environment
2. Close the message box and the DOS window to return to your programming environment
Conditional Returns
A function is meant to return a value. Sometimes, it will perform some tasks whose results would lead to different results. A function can return only one value (we saw that, by passing arguments by reference, you can make a procedure return more than one value) but you can make it render a result depending on a particular behavior. If a function is requesting an answer from the user, since the user can provide different answers, you can treat each result differently. Consider the following function: Module Exercise Private Function SetMembershipLevel$() Dim MemberAge% MemberAge% = InputBox("Enter the Member's Age") If MemberAge% < 18 Then Return "Teen" ElseIf MemberAge% < 55 Then Return "Adult"
End If End Function Public Function Main() As Integer Dim Membership$ MsgBox("Membership: " & Membership$) Return 0 End Function End Module At first glance, this function looks fine. The user is asked to provide a number. If the user enters a number less than 18 (excluded), the function returns Teen. Here is an example of running the program:
If the user provides a number between 18 (included) and 55, the function returns the Adult. Here is another example of running the program:
What if there is an answer that does not fit those we are expecting? The values that we have returned in the function conform only to the conditional statements and not to the function. Remember that in If Condidion Statement, the Statement executes only if the Condition is true. Here is what will happen. If the user enters a number higher than 55 (excluded), the function will not execute any of the returned statements. This means that the execution will reach the End Function line without encountering a return value. This also indicates to the compiler that you wrote a function that is supposed to return a value, but by the end of the method, it didn't return a value. Here is another example of running the program:
The compiler would produce a warning: Warning 1 Function 'SetMembershipLevel' doesn't return a value on all code paths.
To solve this problem, you have various alternatives. If the function uses an If...Then condition, you can create an Else section that embraces any value other than those validated previously. Here is an example: Module Exercise Private Function SetMembershipLevel$() Dim MemberAge% MemberAge% = InputBox("Enter the Member's Age") If MemberAge% < 18 Then Return "Teen" ElseIf MemberAge% < 55 Then Return "Adult" Else Return "Senior" End If End Function Public Function Main() As Integer Dim Membership$ Membership$ = SetMembershipLevel$() MsgBox("Membership: " & Membership$) Return 0 End Function End Module This time, the Else condition would execute if no value applies to the If or ElseIf conditions and the compiler would not produce a warning. Here is another example of running the program:
An alternative is to provide a last return value just before the End Function line. In this case, if the execution reaches the end of the function, it would still return something but you would know what it returns. This would be done as follows: Private Function SetMembershipLevel$() Dim MemberAge% MemberAge% = InputBox("Enter the Member's Age") If MemberAge% < 18 Then Return "Teen" ElseIf MemberAge% < 55 Then Return "Adult" End If Return "Senior" End Function If the function uses an If condition, both implementations would produce the same result.
Return Name End Function Public Function Main() As Integer Dim EmployeeNumber As Long, EmployeeName As String Dim CustomerName As String Dim RentStartDate As Date, RentEndDate As Date Dim NumberOfDays As Integer Dim RateType As String, RateApplied As Double Dim OrderTotal As Double Dim OrderInvoice As String RateType = "Weekly Rate" RateApplied = 0 OrderTotal = RateApplied EmployeeNumber = CLng(InputBox( "Employee number (who processed this order):", "Bethesda Car Rental", "00000")) EmployeeName = GetEmployeeName(EmployeeNumber) CustomerName = InputBox("Enter Customer Name:", _ "Bethesda Car Rental", "John Doe") RentStartDate = CDate(InputBox("Enter Rent Start Date:", _ "Bethesda Car Rental", #1/1/1900#)) RentEndDate = CDate(InputBox("Enter Rend End Date:", _ "Bethesda Car Rental", #1/1/1900#)) NumberOfDays = DateDiff(DateInterval.Day, RentStartDate, RentEndDate) RateApplied = CDbl(InputBox("Enter Rate Applied:", _ "Bethesda Car Rental", 0)) OrderInvoice = "===========================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Order Processing =-=-==" & vbCrLf & "------------------------------------------------" vbCrLf & _ "Processed by:" & vbTab & EmployeeName & vbCrLf & "Processed for:" & vbTab & CustomerName & vbCrLf & "------------------------------------------------" vbCrLf & "Start Date:" & vbTab & RentStartDate & vbCrLf & "End Date:" & vbTab & RentEndDate & vbCrLf & "Nbr of Days:" & vbTab & NumberOfDays & vbCrLf & "------------------------------------------------" vbCrLf & "Rate Type:" & vbTab & RateType & vbCrLf & "Rate Applied:" & vbTab & RateApplied & vbCrLf & "Order Total:" & vbTab & FormatCurrency(OrderTotal) vbCrLf & "===========================" MsgBox(OrderInvoice, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") Return 0 End Function End Module 2. Execute the application 3. Enter the employee number as 54080, the customer name as Sunil Ajat, the start date as 11/05/2008, the end date as 11/15/2008, and the rate applied 49.95
&
&
&
&
4. Close the message box and the DOS window to return to your programming environment
So far, we have used only strings for the values of the second argument of the Choose() function. In reality, the values of the second argument can be almost anything. One value can be a constant. Another value can be a string. Yet another value can come from calling a function. Here is an example: Module Exercise Private Function ShowContractors$() Return "=-= List of Contractors "Martin Samson" & vbCrLf "Genevive Lam" & vbCrLf "Frank Viel" & vbCrLf & "Henry Rickson" & vbCrLf "Samuel Lott" End Function Public Function Main() As Integer Dim Status As UShort, Result$ Status = 3 Result = Choose(Status, "Employment Status: Full Time", "Employment Status: Part Time", ShowContractors, "Seasonal Employment") MsgBox(Result) Return 0 End Function End Module This would produce: =-=" & vbCrLf & & & &
RateType = "Weekly Rate" RateApplied = 0 OrderTotal = RateApplied EmployeeNumber = CLng(InputBox("Employee number (who processed this order):", "Bethesda Car Rental", "00000")) EmployeeName = GetEmployeeName(EmployeeNumber) CustomerName = InputBox("Enter Customer Name:", "Bethesda Car Rental", "John Doe") Tank = CInt(InputBox("Enter Tank Level:" & vbCrLf & "1. Empty" & vbCrLf & "2. 1/4 Empty" & vbCrLf & "3. 1/2 Full" & vbCrLf & "4. 3/4 Full" & vbCrLf & "5. Full", "Bethesda Car Rental", 1)) TankLevel = Choose(Tank, "Empty", "1/4 Empty", "1/2 Full", "3/4 Full", "Full") RentStartDate = CDate(InputBox("Enter Rent Start Date:", "Bethesda Car Rental", #1/1/1900#)) RentEndDate = CDate(InputBox("Enter Rend End Date:", "Bethesda Car Rental", #1/1/1900#)) NumberOfDays = DateDiff(DateInterval.Day, RentStartDate, RentEndDate) RateApplied = CDbl(InputBox("Enter Rate Applied:", _ "Bethesda Car Rental", 0)) OrderInvoice = "===========================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Order Processing =-=-==" & vbCrLf & "------------------------------------------------" & vbCrLf "Processed by:" & vbTab & EmployeeName & vbCrLf & "Processed for:" & vbTab & CustomerName & vbCrLf & "------------------------------------------------" & vbCrLf "Car Selected:" & vbCrLf & vbTab & "Tank:" & vbTab & TankLevel & vbCrLf & "------------------------------------------------" & vbCrLf "Start Date:" & vbTab & RentStartDate & vbCrLf & "End Date:" & vbTab & RentEndDate & vbCrLf & "Nbr of Days:" & vbTab & NumberOfDays & vbCrLf & "------------------------------------------------" & vbCrLf "Rate Type:" & vbTab & RateType & vbCrLf & "Rate Applied:" & vbTab & RateApplied & vbCrLf & "Order Total:" & vbTab & FormatCurrency(OrderTotal) & vbCrLf "===========================" MsgBox(OrderInvoice, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") Return 0 End Function End Module 2. Eexecute the application 3. Enter the employee number as 22804, the customer name as George Livingstone, the tank level as 2, the start date as 09/15/2008, the end date as 09/19/2008, and the rate applied 65.75
& &
4. Close the message box and the DOS window to return to your programming environment
argument to this function is passed as a list of values. As seen previously, each value is passed as a combination of two values: ConditionXToCheck, StatementX As the function is accessed, the compiler checks each condition. If a condition X is true, its statement is executed. If a condition Y is false, the compiler skips it. You can provide as many of these combinations as you want. Here is an example: Module Exercise Private Enum EmploymentStatus FullTime PartTime Contractor Seasonal End Enum Public Function Main() As Integer Dim Status As EmploymentStatus Dim Result As String Status = EmploymentStatus.Contractor Result = "Unknown" Result = Microsoft.VisualBasic.Switch( Status = EmploymentStatus.FullTime, "Full Time", Status = EmploymentStatus.PartTime, "Part Time", Status = EmploymentStatus.Contractor, "Contractor", Status = EmploymentStatus.Seasonal, "Seasonal") MsgBox("Employment Status: " & Result) Return 0 End Function End Module This would produce:
In a true If...Then...ElseIf...ElseIf condition, we saw that there is a possibility that none of the conditions would fit, in which case you can add a last Else statement. The Switch() function also supports this situation if you are using a number, a character, or a string. To provide this last alternative, instead of a ConditionXToCheck expressionk, enter True, and include the necessary statement. Here is an example: Module Exercise Public Function Main() As Integer Dim Status As UShort Dim Result As String Status = 12 Result = Microsoft.VisualBasic.Switch( Status = 1, "Full Time", Status = 2, "Part Time", Status = 3, "Contractor", Status = 4, "Seasonal", True, "Unknown") MsgBox("Employment Status: " & Result) Return 0 End Function End Module This would produce:
Remember that you can also use True with a character. Here is an example: Module Exercise Public Function Main() As Integer Dim Gender As Char Dim Result As String Gender = "H"
Result = Microsoft.VisualBasic.Switch( Gender = "f", "Female", Gender = "F", "Female", Gender = "m", "Male", Gender = "M", "Male", True, "Unknown") MsgBox("Gender: " & Result) Return 0 End Function End Module This would produce:
"Bethesda Car Rental", #1/1/1900#)) NumberOfDays = DateDiff(DateInterval.Day, RentStartDate, RentEndDate) RateApplied = CDbl(InputBox("Enter Rate Applied:", _ "Bethesda Car Rental", 0)) OrderInvoice = "===========================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Order Processing =-=-==" & vbCrLf & "------------------------------------------------" & vbCrLf "Processed by:" & vbTab & EmployeeName & vbCrLf & "Processed for:" & vbTab & CustomerName & vbCrLf & "------------------------------------------------" & vbCrLf "Car Selected:" & vbCrLf & vbTab & "Tag #:" & vbTab & TagNumber & vbCrLf & vbTab & "Car:" & vbTab & CarSelected & vbCrLf & vbTab & "Tank:" & vbTab & TankLevel & vbCrLf & "------------------------------------------------" & vbCrLf "Start Date:" & vbTab & RentStartDate & vbCrLf & "End Date:" & vbTab & RentEndDate & vbCrLf & "Nbr of Days:" & vbTab & NumberOfDays & vbCrLf & "------------------------------------------------" & vbCrLf "Rate Type:" & vbTab & RateType & vbCrLf & "Rate Applied:" & vbTab & RateApplied & vbCrLf & "Order Total:" & vbTab & FormatCurrency(OrderTotal) & vbCrLf "===========================" MsgBox(OrderInvoice, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") Return 0 End Function End Module 2. Eexecute the application 3. Enter the employee number as 86285, the customer name as Genevieve H. Gomoore, the tag number as 924095, the tank level as 3, the start date as 10/22/2008, the end date as 10/31/2008, and the rate applied 55.50
& &
&
& &
4. Close the message box and the DOS window to return to your programming environment
Previous
Next
Conditional Selections
The Select...Case Statement
Introduction
If you have a large number of conditions to examine, the If...Then...Else statement will go through each one of them. The Visual Basic language offers the alternative of jumping to the statement that applies to the state of the condition. This is done with the Select and Case keywords. The formula of the Select Case statement is: Select Case Expression Case Expression1 Statement1 Case Expression2 Statement2 Case ExpressionX StatementX End Select The statement starts with Select Case and ends with End Select. On the right side of Select Case, enter a value, the Expression factor, that will be used as a tag. The value of Expression can be Boolean value (a Boolean type), a character (Char type), a string (a String type), a natural number (a Byte, an SByte, a Short, a UShort, an Integer, a UInteger, a Long, or a ULong type), a decimal number (a Single, a Double, or a Decimal type), a date or time value (a Date type), an enumeration (an Enum type), or else (an Object type). Inside the Select Case and the End Select lines, you provide one or more sections that each contains a Case keyword followed by a value. The value on the right side of Case, ExpresionX, must be the same type as the value of Expression or it can be implied from it. After the case and its expression, you can write a statement. When this section of code is accessed, the value of Expression is considered. Then the value of Expression is compared to each ExpressionX of each case: a. If the value of Expression1 is equal to that of Expression, then Statement1 is executed. If the value of Expression1 is not equal to that of Expression, then the compiler moves to Expression2 b. If the value of Expression2 is equal to that of Expression, then Statement2 is executed c. This will continue down to the last ExpressionX Here is an example: Module Exercise Public Function Main() As Integer Dim Answer As Byte Answer = CByte(InputBox( _ "One of the following is not a Visual Basic keyword" & vbCrLf & "1) Function" & vbCrLf & "2) Except" & vbCrLf & "3) ByRef" & vbCrLf & "4) Each" & vbCrLf & vbCrLf & "Your Answer? ")) Select Case Answer Case 1 MsgBox("Wrong: Function is a Visual Basic keyword." & vbCrLf & "It is used to create a procedure of a function type") Case 2 MsgBox("Correct: Except is not a keyword in " & vbCrLf & "Visual Basic but __except is a C++ " & vbCrLf & "keyword used in Exception Handling") Case 3 MsgBox("Wrong: ByRef is a Visual Basic keyword used " & vbCrLf & "to pass an argument by reference to a procedure") Case 4 MsgBox("Wrong: The ""Each"" keyword is used in " & vbCrLf & "Visual Basic in a type of looping " & vbCrLf & "used to ""scan"" a list of item.") End Select Return 0 End Function End Module Here is an example of running the program:
"3. Drivable - The car is good enough to drive." & "The customer must know the status of the car " & "and agree to rent it", "Bethesda Car Rental", 1)) Select Case CarStatus Case 1 CarCondition = Case 2 CarCondition = Case 3 CarCondition = Case Else CarCondition = End Select
Tank = CInt(InputBox("Enter Tank Level:" & vbCrLf & "1. Empty" & vbCrLf & "2. 1/4 Empty" & vbCrLf & "3. 1/2 Full" & vbCrLf & "4. 3/4 Full" & vbCrLf & "5. Full", "Bethesda Car Rental", 1)) TankLevel = Choose(Tank, "Empty", "1/4 Empty", "1/2 Full", "3/4 Full", "Full") RentStartDate = CDate(InputBox("Enter Rent Start Date:", "Bethesda Car Rental", #1/1/1900#)) RentEndDate = CDate(InputBox("Enter Rend End Date:", "Bethesda Car Rental", #1/1/1900#)) NumberOfDays = DateDiff(DateInterval.Day, RentStartDate, RentEndDate) RateApplied = CDbl(InputBox("Enter Rate Applied:", "Bethesda Car Rental", 0)) OrderInvoice = "===========================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Order Processing =-=-==" & vbCrLf & "------------------------------------------------" "Processed by:" & vbTab & EmployeeName & vbCrLf & "Processed for:" & vbTab & CustomerName & vbCrLf & "------------------------------------------------" "Car Selected:" & vbCrLf & _ vbTab & "Tag #:" & vbTab & TagNumber & vbCrLf & vbTab & "Car:" & vbTab & CarSelected & vbCrLf & vbTab & "Tank:" & vbTab & TankLevel & vbCrLf & "Car Condition:" & vbTab & CarCondition & vbCrLf & "------------------------------------------------" "Start Date:" & vbTab & RentStartDate & vbCrLf & "End Date:" & vbTab & RentEndDate & vbCrLf & "Nbr of Days:" & vbTab & NumberOfDays & vbCrLf & "------------------------------------------------" "Rate Type:" & vbTab & RateType & vbCrLf & "Rate Applied:" & vbTab & RateApplied & vbCrLf & "Order Total:" & vbTab & FormatCurrency(OrderTotal) "===========================" MsgBox(OrderInvoice, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") Return 0 End Function End Module 6. Execute the application 7. Enter the employee number as 92746, the customer name as Antoinette D. Liel, the tag number as 297419, the car condition as 1, the tank level as 5, the start date as 11/15/2008, the end date as 11/17/2008, and the rate applied 65.75
8. Close the message box and the DOS window to return to your programming environment
Combining Cases
As mentioned in our introduction, the Select Case can use a value other than an integer. For example you can use a character. Here is an example: Module Exercise Public Function Main() As Integer Dim Gender As Char Gender = "M" Select Case Gender Case "F" MsgBox("Female") Case "M" MsgBox("Male") Case Else MsgBox("Unknown") End Select Return 0 End Function End Module This would produce:
Notice that in this case we are using only upper case characters. If want to validate lower case characters also, we may have to create additional case sections for each. Here is an example: Module Exercise Public Function Main() As Integer Dim Gender As Char Gender = "f" Select Case Gender Case "f" MsgBox("Female") Case "F" MsgBox("Female") Case "m" MsgBox("Male") Case "M" MsgBox("Male") Case Else MsgBox("Unknown") End Select Return 0 End Function
Instead of using one value for a case, you can apply more than one. To do this, on the right side of the Case keyword, you can separate the expressions with commas. Here are examples: Module Exercise Public Function Main() As Integer Dim Gender As Char Gender = "F" Select Case Gender Case "f", "F" MsgBox("Female") Case "m", "M" MsgBox("Male") Case Else MsgBox("Unknown") End Select Return 0 End Function End Module
You start with the Is keyword. It is followed by one of the Boolean operators we saw in the previous lessons: =, <>, <, <=, >, or >=. On the right side of the boolean operator, type the desired value. Here are examples: Module Exercise Public Function Main() As Integer Dim Number As Short Number = -448 Select Case Number Case Is < 0 MsgBox("The number is negative") Case Is > 0 MsgBox("The number is positive") Case Else MsgBox("0") End Select Return 0 End Function End Module Although we used a natural number here, you can use any appropriate logical comparison that can produce a True or a False result. You can also combine it with the other alternatives we saw previously, such as separating the expressions of a case with commas.
"3. Drivable - The car is good enough to drive." & "The customer must know the status of the car " & "and agree to rent it", "Bethesda Car Rental", 1)) Select Case CarStatus Case 1 CarCondition = Case 2 CarCondition = Case 3 CarCondition = Case Else CarCondition = End Select
Tank = CInt(InputBox("Enter Tank Level:" & vbCrLf & "1. Empty" & vbCrLf & "2. 1/4 Empty" & vbCrLf & "3. 1/2 Full" & vbCrLf & "4. 3/4 Full" & vbCrLf & "5. Full", "Bethesda Car Rental", 1)) TankLevel = Choose(Tank, "Empty", "1/4 Empty", "1/2 Full", "3/4 Full", "Full") RentStartDate = CDate(InputBox("Enter Rent Start Date:", "Bethesda Car Rental", #1/1/1900#)) RentEndDate = CDate(InputBox("Enter Rend End Date:", "Bethesda Car Rental", #1/1/1900#)) NumberOfDays = DateDiff(DateInterval.Day, RentStartDate, RentEndDate) RateApplied = CDbl(InputBox("Enter Rate Applied:", "Bethesda Car Rental", 0)) Dim TemporaryRate As Double Select Case NumberOfDays Case 0, 1 RateType = "Daily Rate" OrderTotal = RateApplied Case 2 RateType = "Weekend Rate" TemporaryRate = RateApplied * 50 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * 2 Case 2 To 7 RateType = "Weekly Rate" TemporaryRate = RateApplied * 25 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * NumberOfDays Case Is > 8 RateType = "Monthly Rate" TemporaryRate = RateApplied * 15 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * NumberOfDays End Select OrderInvoice = "===========================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Order Processing =-=-==" & vbCrLf & "------------------------------------------------" "Processed by:" & vbTab & EmployeeName & vbCrLf & "Processed for:" & vbTab & CustomerName & vbCrLf & "------------------------------------------------" "Car Selected:" & vbCrLf & vbTab & "Tag #:" & vbTab & TagNumber & vbCrLf & vbTab & "Car:" & vbTab & CarSelected & vbCrLf & vbTab & "Tank:" & vbTab & TankLevel & vbCrLf & "Car Condition:" & vbTab & CarCondition & vbCrLf & "------------------------------------------------" "Start Date:" & vbTab & RentStartDate & vbCrLf & "End Date:" & vbTab & RentEndDate & vbCrLf & "Nbr of Days:" & vbTab & NumberOfDays & vbCrLf & "------------------------------------------------" "Rate Type:" & vbTab & RateType & vbCrLf & "Rate Applied:" & vbTab & RateApplied & vbCrLf & "Order Total:" & vbTab & FormatCurrency(OrderTotal) "===========================" MsgBox(OrderInvoice, _ MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") Return 0 End Function End Module 2. Execute the application 3. Enter the employee number as 86285, the customer name as Franco Bolero, the tag number as M931429, the car condition as 3, the tank level as 1, the start date as 10/06/2008, the end date as 11/07/2008, and the rate applied 85.50
4. Close the message box and the DOS window to return to your programming environment
MembershipType = Choose(Number, "Teen", "Adult", "Senior") MsgBox("Membership Type: " & MembershipType) Return 0 End Function End Module
Loops Repeaters
Introduction
A loop is a technique used to repeat an action. The Visual Basic language presents many variations of loops. They combine the Do and the Loop keywords.
"Weekly Hours:" & vbTab & FormatNumber(WeeklyHours) & vbCrLf & "Regular Pay:" & vbTab & FormatCurrency(RegularPay) & vbCrLf & "Overtime Pay:" & vbTab & FormatCurrency(OvertimePay) & vbCrLf & "Total Pay:" & vbTab & FormatCurrency(NetPay) & vbCrLf & "======================" MsgBox(Payroll, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") Return 0 End Function End Module 5. Execute the application to test it 6. Close the form and the DOS window to return to your programming environment
This compiler first executes the Statement or Statements. After executing the Statement(s) section, the compiler checks the Condition. If the Condition is true, then the compiler returns to the Statement(s) and execute(s) it(them). The compiler keeps doing this check-execution gymnastic. As long as the Condition is true, the Statement(s) section will be executed and the Condition will be tested again. If the Condition is false or once the condition becomes false, the statement will not be executed and the program will move on. Here is an example: Module Exercise Public Function Main() As Integer Dim Answer As String Do Answer = InputBox("Are we there yet (1=Yes/0=No)? ") Loop While Answer <> "1" MsgBox("Wonderful, we have arrived") Return 0 End Function End Module Here is an example of running the program:
As you may guess already, the Condition must provide a way for it to be true or to be false. Otherwise, the looping would be executed over and over again.
End If If WeeklyHours < 40 Then RegularTime = WeeklyHours Overtime = 0 RegularPay = HourlySalary * RegularTime OvertimePay = 0 NetPay = RegularPay Else RegularTime = 40 Overtime = WeeklyHours - 40 RegularPay = HourlySalary * 40 OvertimePay = HourlySalary * Overtime NetPay = RegularPay + OvertimePay End If Payroll = "======================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Employee Payroll =-=-==" & vbCrLf & "-------------------------------------------" & vbCrLf & "Employee Name:" & vbTab & EmployeeName & vbCrLf & "Hourly Salary:" & vbTab & FormatCurrency(HourlySalary) & vbCrLf & "Weekly Hours:" & vbTab & FormatNumber(WeeklyHours) & vbCrLf & "Regular Pay:" & vbTab & FormatCurrency(RegularPay) & vbCrLf & "Overtime Pay:" & vbTab & FormatCurrency(OvertimePay) & vbCrLf & "Total Pay:" & vbTab & FormatCurrency(NetPay) & vbCrLf & "======================" MsgBox(Payroll, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") Answer = InputBox("Do you want to create another payroll (y=Yes/n=No)?") Loop While Answer.ToUpper() = "Y" Return 0 End Function End Module 2. Execute the application and create a payroll 3. When asked whether you want to create another payroll, enter y and create another payroll 4. When asked whether you want to create another payroll, enter y again and create another payroll 5. When asked whether you want to create another payroll, enter q 6. Close the form and return to your programming environment
4. Accept to change the name of the module and change the document as follows: Module BethesdaCarRental Private Function GetEmployeeName(ByVal EmplNbr As Long) As String Dim Name As String If EmplNbr = 22804 Then Name = "Helene Mukoko" ElseIf EmplNbr = 92746 Then Name = "Raymond Kouma" ElseIf EmplNbr = 54080 Then Name = "Henry Larson" ElseIf EmplNbr = 86285 Then Name = "Gertrude Monay" Else Name = "Unknown" End If Return Name End Function Public Function Main() As Integer Dim EmployeeNumber As Long, EmployeeName As String Dim CustomerName As String Dim TagNumber As String, CarSelected As String Dim CarStatus As Integer, CarCondition As String Dim Tank As Integer, TankLevel As String Dim RentStartDate As Date, RentEndDate As Date Dim NumberOfDays As Integer Dim RateType As String, RateApplied As Double Dim OrderTotal As Double Dim OrderInvoice As String Dim Answer As MsgBoxResult RateType = "Weekly Rate" RateApplied = 0 OrderTotal = RateApplied Do EmployeeNumber = CLng(InputBox("Employee number (who processed this order):", "Bethesda Car Rental", "00000")) EmployeeName = GetEmployeeName(EmployeeNumber) CustomerName = InputBox("Enter Customer Name:", "Bethesda Car Rental", "John Doe") TagNumber = InputBox("Enter the tag number of the car to rent:", "Bethesda Car Rental", "000000") CarSelected = Microsoft.VisualBasic.Switch( TagNumber = "297419", "BMW 335i", TagNumber = "485M270", "Chevrolet Avalanche", TagNumber = "247597", "Honda Accord LX", TagNumber = "924095", "Mazda Miata", TagNumber = "772475", "Chevrolet Aveo", TagNumber = "M931429", "Ford E150XL", TagNumber = "240759", "Buick Lacrosse", True, "Unidentified Car") CarStatus = CInt(InputBox("After inpecting it, enter car condition:" & vbCrLf & "1. Excellent - No scratch, no damage, no concern" & vbCrLf & "2. Good - Some concerns (scratches or missing something)." & "Make sure the customer is aware." & vbCrLf & "3. Drivable - The car is good enough to drive." & "The customer must know the status of the car " & "and agree to rent it", "Bethesda Car Rental", 1)) Select Case CarStatus Case 1 CarCondition = Case 2 CarCondition = Case 3 CarCondition = Case Else CarCondition = End Select
Tank = CInt(InputBox("Enter Tank Level:" & vbCrLf & "1. Empty" & vbCrLf & "2. 1/4 Empty" & vbCrLf & "3. 1/2 Full" & vbCrLf & "4. 3/4 Full" & vbCrLf & "5. Full", "Bethesda Car Rental", 1)) TankLevel = Choose(Tank, "Empty", "1/4 Empty", "1/2 Full", "3/4 Full", "Full") RentStartDate = CDate(InputBox("Enter Rent Start Date:", "Bethesda Car Rental", #1/1/1900#)) RentEndDate = CDate(InputBox("Enter Rend End Date:", "Bethesda Car Rental", #1/1/1900#))
NumberOfDays = DateDiff(DateInterval.Day, RentStartDate, RentEndDate) RateApplied = CDbl(InputBox("Enter Rate Applied:", "Bethesda Car Rental", 0)) Dim TemporaryRate As Double Select Case NumberOfDays Case 0, 1 RateType = "Daily Rate" OrderTotal = RateApplied Case 2 RateType = "Weekend Rate" TemporaryRate = RateApplied * 50 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * 2 Case 2 To 7 RateType = "Weekly Rate" TemporaryRate = RateApplied * 25 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * NumberOfDays Case Is > 8 RateType = "Monthly Rate" TemporaryRate = RateApplied * 15 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * NumberOfDays End Select OrderInvoice = "===========================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Order Processing =-=-==" & vbCrLf & "------------------------------------------------" & vbCrLf & "Processed by:" & vbTab & EmployeeName & vbCrLf & "Processed for:" & vbTab & CustomerName & vbCrLf & "------------------------------------------------" & vbCrLf & "Car Selected:" & vbCrLf & _ vbTab & "Tag #:" & vbTab & TagNumber & vbCrLf & vbTab & "Car:" & vbTab & CarSelected & vbCrLf & vbTab & "Tank:" & vbTab & TankLevel & vbCrLf & "Car Condition:" & vbTab & CarCondition & vbCrLf & "------------------------------------------------" & vbCrLf & "Start Date:" & vbTab & RentStartDate & vbCrLf & "End Date:" & vbTab & RentEndDate & vbCrLf & "Nbr of Days:" & vbTab & NumberOfDays & vbCrLf & "------------------------------------------------" & vbCrLf & "Rate Type:" & vbTab & RateType & vbCrLf & _ "Rate Applied:" & vbTab & FormatCurrency(RateApplied) & vbCrLf & "Order Total:" & vbTab & FormatCurrency(OrderTotal) & vbCrLf & "===========================" MsgBox(OrderInvoice, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") Answer = MsgBox("Do you want to process another order?", MsgBoxStyle.Information Or MsgBoxStyle.YesNo, "Bethesda Car Rental") Loop Until Answer = MsgBoxResult.No Return 0 End Function End Module 5. Execute the application 6. Enter the employee number as 92746, the customer name as James Wiley, the tag number as 297419, the car condition as 1, the tank level as 5, the start date as 11/07/2008, the end date as 11/10/2008, and the rate applied 49.95
7. When asked whether you want to process another order, click Yes 8. Enter the employee number as 54080, the customer name as Sunil Ajat, the tag number as 240759, the car condition as 3, the tank level as 3, the start date as 11/05/2008, the end date as 11/15/2008, and the rate applied 70.25
9. When asked whether you want to process another order, click Yes 10. Enter the employee number as 22804, the customer name as George Livingstone, the tag number as 924095, the car condition as 2, the tank level as 4, the start date as 09/15/2008, the end date as 09/19/2008, and the rate applied 65.75 11. When asked whether you want to process another order, click Yes 12. Enter the employee number as 86285, the customer name as Antoinette D. Liel, the tag number as 485M270, the car condition as 2, the tank level as 2, the start date as 11/15/2008, the end date as 11/17/2008, and the rate applied 55.50 13. When asked whether you want to process another order, click No 14. Close the message box and the DOS window to return to your programming environment
executes the Statement(s) and checks the Condition again. If the Condition is false, or when the Condition becomes false, the compiler skips the Statement(s) section and continues with the code below the Loop keyword. Here is an example: Module Exercise Public Function Main() As Integer Dim Number As Short Do While Number < 46 Number += CShort(InputBox("Enter a number")) Loop MsgBox("Counting Stopped at: " & Number) Return 0 End Function End Module
Loop Counters
Introduction
The looping statements we reviewed above are used when you don't know or can't anticipate the number of times a condition needs to be checked in order to execute a statement. If you know with certainty how many times you want to execute a statement, you can use another form of loops that use the For...Next expression.
End Module
Previous
Next
Name = "Helene Mukoko" ElseIf EmplNbr = 92746 Then Name = "Raymond Kouma" ElseIf EmplNbr = 54080 Then Name = "Henry Larson" ElseIf EmplNbr = 86285 Then Name = "Gertrude Monay" Else Name = "Unknown" End If Return Name End Function Public Function Main() As Integer Dim EmployeeNumber As Long, EmployeeName As String Dim CustomerName As String Dim TagNumber As String, CarSelected As String Dim RentStartDate As Date, RentEndDate As Date Dim NumberOfDays As Integer Dim RateType As String, RateApplied As Double Dim OrderTotal As Double Dim OrderInvoice As String Dim Answer As MsgBoxResult RateType = "Weekly Rate" RateApplied = 0 OrderTotal = RateApplied Do EmployeeNumber = CLng(InputBox("Employee number (who processed this order):", "Bethesda Car Rental", "00000")) EmployeeName = GetEmployeeName(EmployeeNumber) CustomerName = InputBox("Enter Customer Name:", "Bethesda Car Rental", "John Doe") TagNumber = InputBox("Enter the tag number of the car to rent:", "Bethesda Car Rental", "000000") CarSelected = Microsoft.VisualBasic.Switch( TagNumber = "297419", "BMW 335i", TagNumber = "485M270", "Chevrolet Avalanche", TagNumber = "247597", "Honda Accord LX", TagNumber = "924095", "Mazda Miata", TagNumber = "772475", "Chevrolet Aveo", TagNumber = "M931429", "Ford E150XL", TagNumber = "240759", "Buick Lacrosse", True, "Unidentified Car") RentStartDate = CDate(InputBox("Enter Rent Start Date:", "Bethesda Car Rental", #1/1/1900#)) RentEndDate = CDate(InputBox("Enter Rend End Date:", "Bethesda Car Rental", #1/1/1900#)) NumberOfDays = DateDiff(DateInterval.Day, RentStartDate, RentEndDate) RateApplied = CDbl(InputBox("Enter Rate Applied:", _ "Bethesda Car Rental", 0)) Dim TemporaryRate As Double Select Case NumberOfDays Case 0, 1 RateType = "Daily Rate" OrderTotal = RateApplied Case 2 RateType = "Weekend Rate" TemporaryRate = RateApplied * 50 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * 2 Case 2 To 7 RateType = "Weekly Rate" TemporaryRate = RateApplied * 25 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * NumberOfDays Case Is > 8 RateType = "Monthly Rate" TemporaryRate = RateApplied * 15 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * NumberOfDays End Select OrderInvoice = "===========================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Order Processing =-=-==" & vbCrLf & "------------------------------------------------" & vbCrLf & "Processed by:" & vbTab & EmployeeName & vbCrLf & "Processed for:" & vbTab & CustomerName & vbCrLf & "------------------------------------------------" & vbCrLf & "Car Selected:" & vbCrLf & vbTab & "Tag #:" & vbTab & TagNumber & vbCrLf & vbTab & "Car:" & vbTab & CarSelected & vbCrLf & "------------------------------------------------" & vbCrLf & "Start Date:" & vbTab & RentStartDate & vbCrLf & "End Date:" & vbTab & RentEndDate & vbCrLf & "Nbr of Days:" & vbTab & NumberOfDays & vbCrLf & "------------------------------------------------" & vbCrLf & "Rate Type:" & vbTab & RateType & vbCrLf & "Rate Applied:" & vbTab & FormatCurrency(RateApplied) & vbCrLf &
"Order Total:" & vbTab & FormatCurrency(OrderTotal) & vbCrLf & "===========================" MsgBox(OrderInvoice, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") Answer = MsgBox("Do you want to process another order?", MsgBoxStyle.Information Or MsgBoxStyle.YesNo, "Bethesda Car Rental") Loop Until Answer = MsgBoxResult.No Return 0 End Function End Module 5. Execute the application 6. Enter the employee number as 92746, the customer name as James Wiley, the tag number as 297419, the car condition as 1, the tank level as 5, the start date as 10/22/2008, the end date as 11/07/2008, and the rate applied 49.95
7. When asked whether you want to process another order, click No 8. Close the message box and the DOS window to return to your programming environment
Answer = InputBox(" -=- Multiple Choice Question -=-" & vbCrLf & "To create a constant in your code, " & "you can use the Constant keyword" & vbCrLf & "Your choice (1=True/2=False)? ") If Answer = 1 Then GoTo Wrong If Answer = 2 Then GoTo Right Wrong: Right: Leaving: Return 0 End Function End Module Here is an example of executing the program with Answer = 1: MsgBox("Wrong: The keyword used to create a constant is Const") GoTo Leaving MsgBox("Right: Constant is not a keyword")
Dim OrderTotal As Double Dim OrderInvoice As String Dim Answer As MsgBoxResult RateType = "Weekly Rate" RateApplied = 0 OrderTotal = RateApplied Do EmployeeNumber = CLng(InputBox("Employee number (who processed this order):", _ "Bethesda Car Rental", "00000")) EmployeeName = GetEmployeeName(EmployeeNumber) CustomerName = InputBox("Enter Customer Name:", "Bethesda Car Rental", "John Doe") TagNumber = InputBox("Enter the tag number of the car to rent:", _ "Bethesda Car Rental", "000000") CarSelected = Microsoft.VisualBasic.Switch( TagNumber = "297419", "BMW 335i", TagNumber = "485M270", "Chevrolet Avalanche", TagNumber = "247597", "Honda Accord LX", TagNumber = "924095", "Mazda Miata", TagNumber = "772475", "Chevrolet Aveo", TagNumber = "M931429", "Ford E150XL", TagNumber = "240759", "Buick Lacrosse", True, "Unidentified Car") RentStartDate = CDate(InputBox("Enter Rent Start Date:", "Bethesda Car Rental", #1/1/1900#)) RentEndDate = CDate(InputBox("Enter Rend End Date:", "Bethesda Car Rental", #1/1/1900#)) If RentEndDate < RentStartDate Then MsgBox("The values you entered for the start and end dates " & "are not consecute. The rent start date must occur " & "prior to the rent end date", MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") GoTo RestartOrderProcessing End If NumberOfDays = DateDiff(DateInterval.Day, RentStartDate, RentEndDate) RateApplied = CDbl(InputBox("Enter Rate Applied:", "Bethesda Car Rental", 0)) Dim TemporaryRate As Double Select Case NumberOfDays Case 0, 1 RateType = "Daily Rate" OrderTotal = RateApplied Case 2 RateType = "Weekend Rate" TemporaryRate = RateApplied * 50 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * 2 Case 2 To 7 RateType = "Weekly Rate" TemporaryRate = RateApplied * 25 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * NumberOfDays Case Is > 8 RateType = "Monthly Rate" TemporaryRate = RateApplied * 15 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * NumberOfDays End Select OrderInvoice = "===========================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Order Processing =-=-==" & vbCrLf & "------------------------------------------------" & "Processed by:" & vbTab & EmployeeName & vbCrLf & "Processed for:" & vbTab & CustomerName & vbCrLf & "------------------------------------------------" & "Car Selected:" & vbCrLf & vbTab & "Tag #:" & vbTab & TagNumber & vbCrLf & vbTab & "Car:" & vbTab & CarSelected & vbCrLf & "------------------------------------------------" & "Start Date:" & vbTab & RentStartDate & vbCrLf & "End Date:" & vbTab & RentEndDate & vbCrLf & "Nbr of Days:" & vbTab & NumberOfDays & vbCrLf & "------------------------------------------------" & "Rate Type:" & vbTab & RateType & vbCrLf & "Rate Applied:" & vbTab & FormatCurrency(RateApplied) & "Order Total:" & vbTab & FormatCurrency(OrderTotal) & "===========================" MsgBox(OrderInvoice, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") RestartOrderProcessing: Answer = MsgBox("Do you want to process another order?", MsgBoxStyle.Information Or MsgBoxStyle.YesNo, "Bethesda Car Rental")
vbCrLf &
Loop Until Answer = MsgBoxResult.No Return 0 End Function End Module 2. Execute the application 3. Enter the employee number as 92746, the customer name as James Wiley, the tag number as 297419, the car condition as 1, the tank level as 5, the start date as 10/22/2008, the end date as 11/07/2008, and the rate applied 49.95 4. When asked whether you want to process another order, click Yes 5. Enter the employee number as 92746, the customer name as James Wiley, the tag number as 297419, the car condition as 1, the tank level as 5, the start date as 11/07/2008, the end date as 11/10/2008, and the rate applied 49.95 6. When asked whether you want to process another order, click No 7. Close the message box and the DOS window to return to your programming environment
In this case, the Not operator is used to change the logical value of the variable. When a Boolean variable has been "notted", its logical value has changed. If the logical value was True, it would be changed to False and vice versa. Therefore, you can inverse the logical value of a Boolean variable by "notting" or not "notting" it. Now consider the following program we saw in Lesson 11: Module Exercise Public Function Main() As Integer Dim IsMarried As Boolean Dim TaxRate As Double TaxRate = 33.0 MsgBox("Tax Rate: " & TaxRate & "%") IsMarried = True If IsMarried = True Then TaxRate = 30.65 MsgBox("Tax Rate: " & TaxRate & "%") End If Return 0 End Function End Module
Probably the most classic way of using the Not operator consists of reversing a logical expression. To do this, you precede the logical expression with the Not operator. Here is an example: Module Exercise Public Function Main() As Integer Dim IsMarried As Boolean Dim TaxRate As Double TaxRate = 33.0 MsgBox("Tax Rate: " & TaxRate & "%") IsMarried = True If Not IsMarried Then TaxRate = 30.65 MsgBox("Tax Rate: " & TaxRate & "%") End If Return 0 End Function End Module This would produce:
In some cases, you may want to exit a conditional statement or a loop before its end. To assist with with this, the Visual Basic language provides the Exit keyword. This keyword works like an operator. It can be applied to a procedure or a For loop. Consider the following ShowNames procedure: Module Exercise Private Sub ShowNames() MsgBox("Patricia Katts") MsgBox("Gertrude Monay") MsgBox("Hermine Nkolo") MsgBox("Paul Bertrand Yamaguchi") End Sub Public Function Main() As Integer ShowNames() Return 0 End Function End Module When the procedure is called, it displays four message boxes that each shows a name. Imagine that at some point you want to ask the compiler to stop in the middle of a procedure. To do this, in the section where you want to stop the flow of a procedure, type Exit Sub. Here is an example: Module Exercise Private Sub ShowNames() MsgBox("Patricia Katts") MsgBox("Gertrude Monay") Exit Sub MsgBox("Hermine Nkolo") MsgBox("Paul Bertrand Yamaguchi") End Sub Public Function Main() As Integer ShowNames() Return 0 End Function End Module This time, when the program runs, the ShowNames procedure would be accessed and would start displaying the message boxes. After displaying two, the Exit Sub would ask the compiler to stop and get out of the procedure. Because a function is just a type of procedure that is meant to return a value, you can use the Exit keyword to get out of a function before the End Function line. To do this, in the section where you want to stop the flow of the function, type Exit Function.
Exiting a Do Loop
You can also use the Exit operator to get out of a Do loop. To do this, inside of a Do loop where you want to stop, type Exit Do.
Logical Conjunction
Introduction
As mentioned already, you can nest one conditional statement inside of another. To illustrate, imagine you create a program that would be used by a real estate company that sells houses. You may face a customer who wants to purchase a single family house but the house should not cost over $550,001. To implement this scenario, you can first write a program that asks the user to select a type of house and then a conditional statement would check the type of house. Here is an example: Module Exercise Public Function Main() As Integer Dim Type As String Dim Choice As Integer Dim Value As Double Type = "Unknown" Choice = CInt(InputBox("Enter the type of house you want to purchase" & vbCrLf & "1. Single Family" & vbCrLf & "2. Townhouse" & vbCrLf & "3. Condominium" & vbCrLf & vbCrLf & "You Choice? ")) Value = CDbl(InputBox("Up to how much can you afford?")) Type = Choose(Choice, "Single Family", "Townhouse", "Condominium") Return 0 End Function End Module If the user selects a single family, you can then write code inside the conditional statement of the single family. Here is an example: Module Exercise Public Function Main() As Integer Dim Type As String Dim Choice As Integer Dim Value As Double Type = "Unknown" Choice = CInt(InputBox("Enter the type of house you want to purchase" & vbCrLf & "1. Single Family" & vbCrLf & "2. Townhouse" & vbCrLf & "3. Condominium" & vbCrLf & vbCrLf & "You Choice? ")) Value = CDbl(InputBox("Up to how much can you afford?")) Type = Choose(Choice, "Single Family", "Townhouse", "Condominium") If Choice = 1 Then MsgBox("Desired House Type: "Maximum value afforded: End If Return 0 End Function End Module In that section, you can then write code that would request and check the value the user entered. If that value is valid, you can take necessary action. Here is an example: Module Exercise Public Function Main() As Integer Dim Type As String Dim Choice As Integer Dim Value As Double Type = "Unknown" Choice = CInt(InputBox("Enter the type of house you want to purchase" & vbCrLf & "1. Single Family" & vbCrLf & "2. Townhouse" & vbCrLf & "3. Condominium" & vbCrLf & vbCrLf & "You Choice? ")) Value = CDbl(InputBox("Up to how much can you afford?")) " & vbTab & Type & vbCrLf & " & vbTab & FormatCurrency(Value))
Type = Choose(Choice, "Single Family", "Townhouse", "Condominium") If Choice = 1 Then MsgBox("Desired House Type: " & vbTab & Type & vbCrLf & "Maximum value afforded: " & vbTab & FormatCurrency(Value)) If Value <= 550000 Then MsgBox("Desired House Matched") Else MsgBox("The House Doesn't Match the Desired Criteria") End If End If Return 0 End Function End Module
A Conditional Conjunction
Using conditional nesting, we have seen how you can write one conditional that depends on another. But you must write one first condition, check it, then nest the other condition. This works fine and there is nothing against it. To provide with with an alternative, you can use what is referred to as a logical conjunction. It consists of writing one If...Then expression that checks two conditions at the same time. To illustrate, once again consider a customer who wants to purchase a single family home that is less than $550,000. You can consider two statements as follows: 1. The house is single family 2. The house costs less than $550,000 To implement it, you would need to write an If...Then condition as: If The house is single family AND The house costs less than $550,000 Then Validate End If In the Visual Basic language, the operator used to perform a logical conjunction is And. Here is an example of using it: Module Exercise Public Function Main() As Integer Dim Type As String Dim Choice As Integer Dim Value As Double Type = "Unknown" Choice = _ CInt(InputBox("Enter the type of house you want to purchase" & vbCrLf & "1. Single Family" & vbCrLf & "2. Townhouse" & vbCrLf & "3. Condominium" & vbCrLf & vbCrLf & "You Choice? ")) Value = CDbl(InputBox("Up to how much can you afford?")) Type = Choose(Choice, "Single Family", "Townhouse", "Condominium") If Type = "Single Family" And Value <= 550000 Then MsgBox("Desired House Type: " & vbTab & Type & vbCrLf & "Maximum value afforded: " & vbTab & FormatCurrency(Value)) MsgBox("Desired House Matched") Else MsgBox("The House Doesn't Match the Desired Criteria") End If Return 0 End Function End Module By definition, a logical conjunction combines two conditions. To make the program easier to read, each side of the conditions can be included in parentheses. Here is an example: Module Exercise Public Function Main() As Integer . . . No Change If (Type = "Single Family") And (Value <= 550000) Then MsgBox("Desired House Type: " & vbTab & Type & vbCrLf & "Maximum value afforded: " & vbTab & FormatCurrency(Value)) MsgBox("Desired House Matched") Else MsgBox("The House Doesn't Match the Desired Criteria") End If Return 0
To understand how logical conjunction works, from a list of real estate properties, after selecting the house type, if you find a house that is a single family home, you put it in the list of considered properties: Type of House The house is single family House True
If you find a house that is less than or equal to $550,000, you retain it: Price Range $550,000 Value True
For the current customer, you want a house to meet BOTH criteria. If the house is a town house, based on the request of our customer, its conditional value is false. If the house is less than $550,000, such as $485,000, the value of the Boolean Value is true:
If the house is a town house, based on the request of our customer, its conditional value is false. If the house is more than $550,000, the value of the Boolean Value is true. In logical conjunction, if one of the conditions is false, the result if false also. This can be illustrated as follows: Type of House Town House False House Value $625,000 False Result Town House AND $625,000 False
Suppose we find a single family home. The first condition is true for our customer. With the AND Boolean operator, if the first condition is true, then we consider the second criterion. Suppose that the house we are considering costs $750,500: the price is out of the customer's range. Therefore, the second condition is false. In the AND Boolean algebra, if the second condition is false, even if the first is true, the whole condition is false. This would produce the following table: Type of House Single Family True House Value $750,500 False Result Single Family AND $750,500 False
Suppose we find a townhouse that costs $420,000. Although the second condition is true, the first is false. In Boolean algebra, an AND operation is false if either condition is false: Type of House Town House False House Value $420,000 True Result Town House AND $420,000 False
If we find a single family home that costs $345,000, both conditions are true. In Boolean algebra, an AND operation is true if BOTH conditions are true. This can be illustrated as follows: Type of House Single Family True House Value $345,000 True Result Single Family AND $345,000 True
These four tables can be resumed as follows: Condition1 AND Condition2 False False False True
If Condition1 is If Condition2 is False False True True False True False True
As you can see, a logical conjunction is true only of BOTH conditions are true.
Loop Until (Status > 0) And (Status < 4) Return Condition End Function
Public Function Main() As Integer Dim EmployeeNumber As Long, EmployeeName As String Dim CustomerName As String Dim TagNumber As String, CarSelected As String Dim CarCondition As String Dim RentStartDate As Date, RentEndDate As Date Dim NumberOfDays As Integer Dim RateType As String, RateApplied As Double Dim OrderTotal As Double Dim OrderInvoice As String Dim Answer As MsgBoxResult RateType = "Weekly Rate" RateApplied = 0 OrderTotal = RateApplied Do EmployeeNumber = CLng(InputBox("Employee number (who processed this order):", "Bethesda Car Rental", "00000")) EmployeeName = GetEmployeeName(EmployeeNumber) CustomerName = InputBox("Enter Customer Name:", "Bethesda Car Rental", "John Doe") TagNumber = InputBox("Enter the tag number of the car to rent:", "Bethesda Car Rental", "000000") CarSelected = Microsoft.VisualBasic.Switch( TagNumber = "297419", "BMW 335i", TagNumber = "485M270", "Chevrolet Avalanche", TagNumber = "247597", "Honda Accord LX", TagNumber = "924095", "Mazda Miata", TagNumber = "772475", "Chevrolet Aveo", TagNumber = "M931429", "Ford E150XL", TagNumber = "240759", "Buick Lacrosse", True, "Unidentified Car") CarCondition = GetCarCondition() RentStartDate = CDate(InputBox("Enter Rent Start Date:", "Bethesda Car Rental", #1/1/1900#)) RentEndDate = CDate(InputBox("Enter Rend End Date:", "Bethesda Car Rental", #1/1/1900#)) If RentEndDate < RentStartDate Then MsgBox("The values you entered for the start and end dates " & "are not consecute. The rent start date must occur " & "prior to the rent end date", MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") GoTo RestartOrderProcessing End If NumberOfDays = DateDiff(DateInterval.Day, RentStartDate, RentEndDate) RateApplied = CDbl(InputBox("Enter Rate Applied:", "Bethesda Car Rental", 0)) Dim TemporaryRate As Double Select Case NumberOfDays Case 0, 1 RateType = "Daily Rate" OrderTotal = RateApplied Case 2 RateType = "Weekend Rate" TemporaryRate = RateApplied * 50 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * 2 Case 2 To 7 RateType = "Weekly Rate" TemporaryRate = RateApplied * 25 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * NumberOfDays Case Is > 8 RateType = "Monthly Rate" TemporaryRate = RateApplied * 15 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * NumberOfDays End Select OrderInvoice = "===========================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Order Processing =-=-==" & vbCrLf & "------------------------------------------------" & vbCrLf & "Processed by:" & vbTab & EmployeeName & vbCrLf & "Processed for:" & vbTab & CustomerName & vbCrLf & "------------------------------------------------" & vbCrLf & "Car Selected:" & vbCrLf & vbTab & "Tag #:" & vbTab & TagNumber & vbCrLf & vbTab & "Car:" & vbTab & CarSelected & vbCrLf & "Car Condition:" & vbTab & CarCondition & vbCrLf & "------------------------------------------------" & vbCrLf & "Start Date:" & vbTab & RentStartDate & vbCrLf & "End Date:" & vbTab & RentEndDate & vbCrLf & "Nbr of Days:" & vbTab & NumberOfDays & vbCrLf & "------------------------------------------------" & vbCrLf & "Rate Type:" & vbTab & RateType & vbCrLf & "Rate Applied:" & vbTab & FormatCurrency(RateApplied) & vbCrLf &
"Order Total:" & vbTab & FormatCurrency(OrderTotal) & vbCrLf & "===========================" MsgBox(OrderInvoice, _ MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") RestartOrderProcessing: Answer = MsgBox("Do you want to process another order?", MsgBoxStyle.Information Or MsgBoxStyle.YesNo, "Bethesda Car Rental") Loop Until Answer = MsgBoxResult.No Return 0 End Function End Module 5. Execute the application 6. Enter the employee number as 92746, the customer name as James Wiley, the tag number as 297419, and the car condition as -5 and click OK
7. Enter the car condition as 8tank level as 5 and press Enter 8. Enter the car condition as 2, the start date as 11/07/2008, the end date as 11/10/2008, and the rate applied 49.95 9. When asked whether you want to process another order, click Yes 10. Enter the employee number as 54080, the customer name as Sunil Ajat, the tag number as 240759, the car condition as 3, the tank level as 3, the start date as 11/05/2008, the end date as 11/15/2008, and the rate applied 70.25 11. When asked whether you want to process another order, click No 12. Close the message box and the DOS window to return to your programming environment
Combining Conjunctions
As seen above, the logical conjunction operator is used to combine two conditions. In some cases, you will need to combine more than two conditions. Imagine a customer wants to purchase a single family house that costs up to $450,000 with an indoor garage. This means that the house must fulfill these three requirements: A. The house is a single family home B. The house costs less than $450,001 C. The house has an indoor garage Here the program that could be used to check these conditions: Module Exercise Public Function Main() As Integer Dim Type As String Dim Choice As Integer Dim Value As Double Dim IndoorGarageAnswer As MsgBoxResult Dim Answer As String Type = "Unknown" Choice = CInt(InputBox("Enter the type of house you want to purchase" & vbCrLf & "1. Single Family" & vbCrLf & "2. Townhouse" & vbCrLf & "3. Condominium" & vbCrLf & vbCrLf & "You Choice? ")) Value = CDbl(InputBox("Up to how much can you afford?")) Type = Choose(Choice, "Single Family", "Townhouse", "Condominium") IndoorGarageAnswer = MsgBox("Does the house have an indoor garage (1=Yes/0=No)? ", MsgBoxStyle.Question Or MsgBoxStyle.YesNo, "Real Estate")
Answer = IIf(IndoorGarageAnswer = MsgBoxResult.Yes, "Yes", "No") If (Type = "Single Family") And (Value <= 550000) And (IndoorGarageAnswer = MsgBoxResult.Yes) Then MsgBox("Desired House Type: " & vbTab & Type & vbCrLf & "Maximum value afforded: " & vbTab & FormatCurrency(Value) & vbCrLf & "House has indoor garage: " & vbTab & Answer) MsgBox("Desired House Matched") Else MsgBox("The House Doesn't Match the Desired Criteria") End If Return 0 End Function End Module We saw that when two conditions are combined, the compiler first checks the first condition, followed by the second. In the same way, if three conditions need to be considered, the compiler evaluates the truthfulness of the first condition: Type of House A Town House False If the first condition (or any condition) is false, the whole condition is false, regardless of the outcome of the other(s). If the first condition is true, then the second condition is evaluated for its truthfulness: Type of House A Single Family True Property Value B $655,000 False
If the second condition is false, the whole combination is considered false: A True B False A && B False
When evaluating three conditions, if either the first or the second is false, since the whole condition would become false, there is no reason to evaluate the third. If both the first and the second conditions are false, there is also no reason to evaluate the third condition. Only if the first two conditions are true will the third condition be evaluated whether it is true: Type of House A Single Family True Property Value Indoor Garage B $425,650 True C None False
The combination of these conditions in a logical conjunction can be written as A && B && C. If the third condition is false, the whole combination is considered false: A True B True A && B True C False A && B && C False
From our discussion so far, the truth table of the combinations can be illustrated as follows: A False True True B Don't Care False True C Don't Care Don't Care False A && B && C False False False
The whole combination is true only if all three conditions are true. This can be illustrated as follows: A False False True True False B False False False False True C False True False True False A && B && C False False False False False
Logical Disjunction: OR
Introduction
Our real estate company has single family homes, townhouses, and condominiums. All of the condos have only one level, also referred to as a story. Some of the single family homes have one story, some have two and some others have three levels. All townhouses have three levels. Another customer wants to buy a home. The customer says that he primarily wants a condo, but if our real estate company doesn't have a condominium, that is, if the company has only houses, whatever it is, whether a house or a condo, it must have only one level (story) (due to an illness, the customer would not climb the stairs). When considering the properties of our company, we would proceed with these statements: 1. The property is a condominium 2. The property has one story If we find a condo, since all of our condos have only one level, the criterion set by the customer is true. Even if we were considering another (type of) property, it wouldn't matter. This can be resumed in the following table: Type of House Condominium House True
The other properties would not be considered, especially if they have more than one story: Number of Stories 3 We can show this operation as follows: Condominium One Story Condominium or 1 Story True False True Value False
Module Exercise Public Function Main() As Integer . . . No Change If (Choice = 1) Or (Stories = 1) Then MsgBox("Desired House Type:" & vbTab & Type & vbCrLf & "Number of Stories:" & vbTab & vbTab & Stories) MsgBox("Desired House Matched") Else MsgBox("The House Doesn't Match the Desired Criteria") End If Return 0 End Function End Module Here is an example of running the program:
Suppose that, among the properties our real estate company has available, there is no condominium. In this case, we would then consider the other properties: Type of House Single Family House False
If we have a few single family homes, we would look for one that has only one story. Once we find one, our second criterion becomes true: Type of House False One Story Condominium OR 1 Story True True
If we find a condo and it is one story, both criteria are true. This can be illustrated in the following table: Type of House False True One Story Condominium OR 1 Story True True True True
A Boolean OR operation produces a false result only if BOTH conditions ARE FALSE: If Condition1 is If Condition2 is False True True False True False True False Condition1 OR Condition2 True True True False
MsgBox("Please enter a valid number between 1 and 3", MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") End If Loop Until (Status > 0) And (Status < 4) Return Condition End Function Private Function GetTankLevel() As String Dim Level As Integer Dim Result As String Do Level = CInt(InputBox("Enter Tank Level:" & vbCrLf & "1. Empty" & vbCrLf & "2. 1/4 Empty" & vbCrLf & "3. 1/2 Full" & vbCrLf & "4. 3/4 Full" & vbCrLf & "5. Full", "Bethesda Car Rental", 1)) Result = Microsoft.VisualBasic.Switch(Level = 1, "Empty", Level = 2, "1/4 Empty", Level = 3, "1/2 Full", Level = 4, "3/4 Full", True, "Full") If (Level < 1) Or (Level > 5) Then MsgBox("Invalid tank level. " & "Please try again.", MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") End If Loop While (Level < 1) Or (Level > 5) Return Result End Function Public Function Main() As Integer Dim EmployeeName As String Dim CustomerName As String Dim TagNumber As String, CarSelected As String Dim CarCondition As String Dim TankLevel As String Dim RentStartDate As Date, RentEndDate As Date Dim NumberOfDays As Integer Dim RateType As String, RateApplied As Double Dim OrderTotal As Double Dim OrderInvoice As String Dim Answer As MsgBoxResult RateApplied = 0 RateType = "Weekly Rate" OrderTotal = RateApplied Do EmployeeName = GetEmployeeName() CustomerName = InputBox("Enter Customer Name:", _ "Bethesda Car Rental", "John Doe") TagNumber = InputBox("Enter the tag number of the car to rent:", "Bethesda Car Rental", "000000") CarSelected = Microsoft.VisualBasic.Switch( TagNumber = "297419", "BMW 335i", TagNumber = "485M270", "Chevrolet Avalanche", TagNumber = "247597", "Honda Accord LX", TagNumber = "924095", "Mazda Miata", TagNumber = "772475", "Chevrolet Aveo", TagNumber = "M931429", "Ford E150XL", TagNumber = "240759", "Buick Lacrosse", True, "Unidentified Car") CarCondition = GetCarCondition() TankLevel = GetTankLevel() RentStartDate = CDate(InputBox("Enter Rent Start Date:", "Bethesda Car Rental", #1/1/1900#)) RentEndDate = CDate(InputBox("Enter Rend End Date:", "Bethesda Car Rental", #1/1/1900#)) If RentEndDate < RentStartDate Then MsgBox("The values you entered for the start and end dates " & "are not consecute. The rent start date must occur " & "prior to the rent end date", MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") GoTo RestartOrderProcessing End If NumberOfDays = DateDiff(DateInterval.Day, RentStartDate, RentEndDate) RateApplied = CDbl(InputBox("Enter Rate Applied:", _ "Bethesda Car Rental", 0)) Dim TemporaryRate As Double Select Case NumberOfDays Case 0, 1
RateType = "Daily Rate" OrderTotal = RateApplied Case 2 RateType = "Weekend Rate" TemporaryRate = RateApplied * 50 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * 2 Case 2 To 7 RateType = "Weekly Rate" TemporaryRate = RateApplied * 25 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * NumberOfDays Case Is > 8 RateType = "Monthly Rate" TemporaryRate = RateApplied * 15 / 100 RateApplied = RateApplied - TemporaryRate OrderTotal = RateApplied * NumberOfDays End Select OrderInvoice = "===========================" & vbCrLf & "=//= BETHESDA CAR RENTAL =//=" & vbCrLf & "==-=-= Order Processing =-=-==" & vbCrLf & "------------------------------------------------" & vbCrLf & "Processed by:" & vbTab & EmployeeName & vbCrLf & "Processed for:" & vbTab & CustomerName & vbCrLf & "------------------------------------------------" & vbCrLf & "Car Selected:" & vbCrLf & vbTab & "Tag #:" & vbTab & TagNumber & vbCrLf & vbTab & "Car:" & vbTab & CarSelected & vbCrLf & vbTab & "Tank:" & vbTab & TankLevel & vbCrLf & "Car Condition:" & vbTab & CarCondition & vbCrLf & "------------------------------------------------" & vbCrLf & "Start Date:" & vbTab & RentStartDate & vbCrLf & "End Date:" & vbTab & RentEndDate & vbCrLf & "Nbr of Days:" & vbTab & NumberOfDays & vbCrLf & "------------------------------------------------" & vbCrLf & "Rate Type:" & vbTab & RateType & vbCrLf & "Rate Applied:" & vbTab & FormatCurrency(RateApplied) & vbCrLf & "Order Total:" & vbTab & FormatCurrency(OrderTotal) & vbCrLf & "===========================" MsgBox(OrderInvoice, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Bethesda Car Rental") RestartOrderProcessing: Answer = MsgBox("Do you want to process another order?", MsgBoxStyle.Information Or MsgBoxStyle.YesNo, "Bethesda Car Rental") Loop Until Answer = MsgBoxResult.No Return 0 End Function End Module 5. Execute the application 6. Enter the employee number as 92746, the customer name as James Wiley, the tag number as 297419, the car condition as 1, the tank level as 5, the start date as 11/07/2008, the end date as 11/10/2008, and the rate applied 49.95 7. When asked whether you want to process another order, click Yes 8. Enter the employee number as 54080, the customer name as Sunil Ajat, the tag number as 240759, the car condition as 3, the tank level as 3, the start date as 11/05/2008, the end date as 11/15/2008, and the rate applied 70.25 9. When asked whether you want to process another order, click Yes 10. Enter the employee number as 22804, the customer name as George Livingstone, the tag number as 924095, the car condition as 2, the tank level as 4, the start date as 09/15/2008, the end date as 09/19/2008, and the rate applied 65.75 11. When asked whether you want to process another order, click Yes 12. Enter the employee number as 86285, the customer name as Antoinette D. Liel, the tag number as 485M270, the car condition as 2, the tank level as 2, the start date as 11/15/2008, the end date as 11/17/2008, and the rate applied 55.50 13. When asked whether you want to process another order, click No 14. Close the message box and the DOS window to return to your programming environment
Combinations of Disjunctions
As opposed to evaluating only two conditions, you may face a situation that presents three of them and must consider a combination of more than two conditions. You would apply the same logical approach we reviewed for the logical conjunction, except that, in a group of logical disjunctions, if one of them is true, the whole statement becomes true.
Previous
Home
Introduction to Classes
Programmer-Defined Types
Introduction
In the Visual Basic language, you can combine a group of variables into an entity. These variables become considered as one. You can then declare one or more elaborate variables from this enhanced type. Such a new type is called a class.
Public Module DepartmentStore Public Function Main() As Integer Return 0 End Function End Module 5. Save the file
Creating a Class
Imagine you want to represent a rectangle as a geometric object:
You can declare each of its various parts as a variable. Here is an example: Public Module Exercise Public Function Main() As Integer Dim RectLength As Double Dim RectHeight As Double RectLength = 24.55 : RectHeight = 20.75 MsgBox("=-= Rectangle Characteristics =-=" & vbCrLf & _ "Length: " & vbTab & RectLength & vbCrLf & _ "Height: " & vbTab & RectHeight) Return 0 End Function End Module This would produce:
If you want to treat the whole rectangle as one object, you can create a class for it. To create a class, you can use the Class keyword followed by a name. The name of a class follows the rules we have applied so far for variable and function names. To declare a class called Rectangle, you would start with the following: Class Rectangle As a name that represents a group of items, a class has a body that would be used to define the items that compose it. The body of a class starts after its name. To indicate the end of the class, type End Class. Therefore, a class can be created as follows: Class Rectangle End Class Since a class is a combination of other variables, you declare each variable inside of the body of the class. Each item that composes the class is represented as a complete variable declared with a name and a data type. By adding a Length and a Height variables, our class would become: Class Rectangle Dim Length As Double Dim Height As Double End Class The items that compose a class are called members of the class. When creating the members of a class, you can omit the Dim keyword: Class Rectangle Length As Double Height As Double End Class To create a class in Microsoft Visual Studio: a. On the main menu, you can click Project -> Add Class... Alternatively, in the Solution Explorer, you can right-click the name of the project, position the mouse on Add, and click Class b. In the Templates section of the Add New Item dialog box, make sure the Class item is selected. Accept the suggested name or replace it in the Name text box
c. Click Add
Each item in this catalog is represented by its Stock number, its name or description, and its price. Based on this, you can create a class that represents each item. 1. To create a new class, on the main menu, click Project -> Add Class... 2. In the Templates section of the Add New Item dialog box, make sure the Class item is selected. Set the Name to StoreItem 3. Click Add 4. Change the document as follows:
Public Class StoreItem Dim ItemNumber As Long Dim ItemName As String Dim UnitPrice As Double End Class 5. Save the file
Public Class StoreItem Friend ItemNumber As Long Friend ItemName As String Friend UnitPrice As Double End Class 2. Save the file
A Private Class
If you create a class in a code file but the class must be accessed only locally, you can define it as private. A class is referred to as private if it can be accessed only within the module where it is created, that is, only by members of the same file. Classes and modules outside of its file or outside of the application cannot access such a class. To create a private class, precede it with the Private keyword. Here is an example: Module Exercise REM This class can be accessed only inside this module Private Class Rectangle Public Length As Double Friend Height As Double End Class Public Function Main() As Integer Return 0 End Function End Module
A Friendly Class
Instead of hiding a class from the rest of the application, you may want other modules or classes of the same application to have access to it. Such a class is referred to as friendly. A friendly class can be accessed by code within its application. Classes and modules outside of its application do not have access to such a class. To create a friendly class, precede it with the Friend keyword. Here is an example: Friend Class Square Public Side As Double End Class
A Public Class
Although you may think of working only in Visual Basic, in some cases, you may create a class and want to share it with code written in another language such as C++/CLI or C#, to make this possible, you can give "public" access to your class. If you want your class to be accessible to code written in other languages, precede the Class keyword with Public when creating it. Here is an example: Public Class Circle Friend Radius As Double End Class
Recto = New Rectangle() Return 0 End Function End Module or like this: Module Exercise Private Class Rectangle Public Length As Double Friend Height As Double End Class Public Function Main() As Integer Dim Recto As New Rectangle() Return 0 End Function End Module
In C#, you must always use parentheses.
Any of these techniques produces the same result. It is just a matter of taste. A variable declared of a class is also called an object.
Public Module DepartmentStore Public Function Main() As Integer Dim dptStore As StoreItem dptStore = New StoreItem Return 0 End Function End Module 2. Save the file
Period: .
After declaring the variable and allocating memory for it, the compiler reserves enough memory to accommodate all the members of the class and those members become available to you. To access the member of a class, type the name of the variable, followed by a period, followed by the name of the member you want. The member you are trying to use must be part of the class. Here is an example: Module Exercise Private Class Rectangle Public Length As Double Friend Height As Double End Class Public Function Main() As Integer Dim Recto As Rectangle Recto.Length Return 0 End Function End Module If you are using either Microsoft Visual Basic or another editor equipped with Intellisense, after you type the period, the list of members would appear:
If you know the name of the member, you can start typing it: Once the desired member is highlighted, press the Space bar or Tab If you see the name of the member in the list, you can double-click click it If the list doesn't appear, press Ctrl + Space bar If you don't want to use the list displayed by the Code Editor, press Esc. Once you have specified what member you want to use, you can assign it the desired value. Here is an example: Module Exercise Private Class Rectangle Public Length As Double Friend Height As Double End Class Public Function Main() As Integer Dim Recto As Rectangle Recto.Length = 24.55 Return 0 End Function End Module In the same way, you can access all the desired members of a class and initialize them to complete the variable. By default, each member variable must be initialized on its own line. Here are examples: Module Exercise Private Class Rectangle Public Length As Double Friend Heigh
Each item in this catalog is represented by its Stock number, its name or description, and its price. Based on this, you can create a class that represents each item.
2. In the Solution Explorer, right-click Module1.vb and click Rename 3. Set the name to DepartmentStore.vb, press Enter, and accept to rename the file 4. Change the document as follows:
Public Module DepartmentStore Public Function Main() As Integer Return 0 End Function End Module 5. Save the file 6. To create a new class, on the main menu, click Project -> Add Class... 7. In the Templates section of the Add New Item dialog box, make sure the Class item is selected. Set the Name to StoreItem 8. Click Add 9. Change the document as follows:
Public Class StoreItem Friend ItemNumber As Long Friend ItemName As String Friend UnitPrice As Double End Class 10. Save the file 11. To use a DepartmentStore object, change the Program.vb file as follows:
Public Module DepartmentStore Public Function Main() As Integer Dim dptStore As StoreItem dptStore = New StoreItem With dptStore .ItemNumber = 437876 .ItemName = "Crinkled Georgette Dress" .UnitPrice = 42.95 MsgBox("=-= Department Store =-=" & vbCrLf & _ "Item #:" & vbTab & vbTab & .ItemNumber & vbCrLf & _ "Item Name:" & vbTab & .ItemName & vbCrLf & _ "Unit Price: " & vbTab & FormatCurrency(.UnitPrice), _ MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _ "Department Store") End With Return 0 End Function End Module 12. Execute the application to test it 13. Click OK and return to your programming environment
Creating a Method
To create a method, in the body of a class, use the same formula we learned in Lesson 5. For example, to create a sub procedure, you use the following formula: Class Class Name Sub ProcedureName() End Sub End Class Here is an example: Private Class Rectangle Sub Show() End Sub
End Class In the body of the method, do whatever you want. For example, you can call the MsgBox() function to display a message. Here is an example: Private Class Rectangle Sub Show() MsgBox("Whatever") End Sub End Class
Public Class StoreItem Friend ItemNumber As Long Friend ItemName As String Friend UnitPrice As Double Sub Create() ItemNumber = 790475 ItemName = "New Wool Comfort Pants" UnitPrice = 38.75 End Sub Sub Display() MsgBox("=-= Department Store =-=" & vbCrLf & _ "Item #:" & vbTab & vbTab & ItemNumber & vbCrLf & _ "Item Name:" & vbTab & ItemName & vbCrLf & _ "Unit Price: " & vbTab & FormatCurrency(UnitPrice), _ MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _ "Department Store") End Sub End Class 3. Save the file
Accessing a Method
To access a method outside of its class, you can use the period operator as we saw for the member variables. Here is an example Public Module Exercise Private Class Rectangle Sub Show() MsgBox("Whatever") End Sub End Class Public Function Main() As Integer Dim Recto As Rectangle Recto = New Rectangle Recto.Show() Return 0 End Function End Module In the same way, you can use a With statement to access a method of a class.
Public Module DepartmentStore Public Function Main() As Integer Dim dptStore As StoreItem dptStore = New StoreItem With dptStore .Create() .Display() End With Return 0 End Function
End Module 3. Execute the application to test it 4. Click OK and return to your programming environment
Friend Class Rectangle Public Length As Double Public Height As Double Function Assign() As Double End Function End Class After declaring a procedure, in its body, you can implement the expected behavior. As seen for a sub procedure, when a method has been created, it has access to all of the other members of the same class. This means that you don't have to re-declare a member of a class to access it in a method. Based on this, you can manipulate any member variable of the same class as you wish. This means that, naturally, you do not have to create a function method to change the value of a member variable. A normal sub procedure can take care of this. Instead, you would create a method if you need to perform a calculation and get a value from it instead of storing that value in one of the member variables. Here is an example: Friend Class Rectangle Public Length As Double Public Height As Double
Function Assign() As Double End Function Function Perimeter() As Double End Function End Class Therefore, in the body of the function, you can access a member variable, you can call another method of the same class, or you can use an external value as you see fit. When the function exits, make sure it returns the appropriate value based on its type. Like the member variables, the methods can be accessed outside of the class using the period operator. Here is an example: Public Module Exercise Friend Class Rectangle Public Length As Double Public Height As Double Function Perimeter() As Double Return (Length + Height) * 2 End Function Function Area#() Return Length * Height End Function End Class Public Function Main() As Integer Dim Recto As Rectangle Recto = New Rectangle Recto.Length = 42.58 : Recto.Height = 28.08 MsgBox("=-= Rectangle Characteristics =-=" & vbCrLf & _ "Length: " & vbTab & vbTab & Recto.Length & vbCrLf & _ "Height: " & vbTab & vbTab & Recto.Height & vbCrLf & _ "Perimeter: " & vbTab & Recto.Perimeter() & vbCrLf & _ "Area: " & vbTab & vbTab & Recto.Area()) Return 0 End Function End Module This would produce:
Like a sub procedure that is created as a method, a member function of a class can be made private, public, or friendly. It follows the exact same rules we reviewed early.
Module DepartmentStore Public Class StoreItem Public ItemNumber As Long Public ItemName As String Public UnitPrice As Double Public Sub RegisterStoreItem() ItemNumber = CLng(InputBox("=#= Department Store =#=" & vbCrLf & _ " --- Item Registration ---" & vbCrLf & _ vbCrLf & vbCrLf & vbCrLf & _ "Enter Item #", "Department Store")) ItemName = InputBox("=#= Department Store =#=" & vbCrLf & _ " --- Item Registration ---" & vbCrLf & _ "Enter Item Name", "Department Store")
" --- Item Registration ---" & vbCrLf & vbCrLf & vbCrLf & _ "Enter Unit Price", "Department Store")) End Sub Public Sub ShowItem() MsgBox("=-= Department Store =-=" & vbCrLf & _ "--- Store Inventory ---" & vbCrLf & _ "Item #:" & vbTab & vbTab & ItemNumber & vbCrLf & _ "Item Name:" & vbTab & ItemName & vbCrLf & _ "Unit Price:" & vbTab & FormatCurrency(UnitPrice), _ MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _ "Department Store") End Sub End Class Public Function Main() As Integer Dim dptStore As StoreItem = New StoreItem dptStore.RegisterStoreItem() dptStore.ShowItem() Return 0 End Function End Module 5. Execute the program to test it 6. Enter the item # as 740797
1.
Methods Overloading
Just as done for regular procedures, a method of a class can be overloaded. To overload a method, create more than one method with the same name. The methods with same names must have different rules in their arguments: They can have different types of arguments. Here is an example:
Private Class EmployeeInformation REM Contractor Registration Private Sub Register(ByVal SalaryCategory As Integer) End Sub REM Full Time Employee Registration Private Sub Register(ByVal HourlySalary As Double) End Sub End Class They can have a different number of arguments. Here is an example:
Private Class Geometry REM The area of a square Friend Function CalculateArea#(ByVal Side#) Area# = Side * Side End Function REM The area of a rectangle Friend Function CalculateArea#(ByVal Length#, ByVal Height#) Area# = Length# * Height# End Function End Class Any or both of these two rules must be respected.
Me
We have mentioned two techniques of accessing the members of a class, one consisted of declaring a variable of the class, the other had to do with Shared members. We know already that the members of a class are made available to all other members of the same class without being declared or qualified. Consider the following class: Public Class Triangle Public Base As Double Public Height As Double Public Area As Double Public Sub Display() Dim Area As Double Area = Base * Height / 2 End Sub End Class When the Area variable is used in the Display() method, there are two variables available and named Area. It makes it confusing to know what particular variable is being accessed. You can use a special member of a class that allows you to specify the member of a class when accessing it. This member is called Me. When using Me, you can access any member of a class within any method of the same class. Here is an example: Public Module Exercise Public Class Triangle Public Base As Double Public Height As Double Public Area As Double Public Sub Display() Dim Area As Double
' Using "this" to access the members of this class Me.Base = 24.55 Me.Height = 20.75 ' You cannot use this to access Area because Area ' is not a member of this class Area = Me.Base * Me.Height / 2 MsgBox("Triangle Characteristics" & vbCrLf & _ "Base:" & vbTab & Me.Base & vbCrLf & _ "Height:" & vbTab & Me.Height & vbCrLf & _ "Area: " & vbTab & Area) ' Area is not a member of the Exercise class End Sub End Class Public Function Main() As Integer Dim tri As Triangle = New Triangle tri.Display() Return 0 End Function End Module This would produce:
There are rules you must follow when using Me: Me can never be declared: it is automatically implied when you create a class Me cannot be used in a class A to access a member of class B Me cannot be used in a Shared method. The following program will not compile because Me is used in the Display() method declared as a Shared method:
Public Class Triangle Public Base As Double Public Height As Double Public Area As Double Public Shared Sub Display() Dim Area As Double ' Using "this" to access the members of this class Me.Base = 24.55 Me.Height = 20.75 ' You cannot use this to access Area because Area ' is not a member of this class Area = Me.Base * Me.Height / 2 MsgBox("Triangle Characteristics" & vbCrLf & _ "Base:" & vbTab & Me.Base & vbCrLf & _ "Height:" & vbTab & Me.Height & vbCrLf & _ "Area: " & vbTab & Area) End Sub End Class
Home
Notice that this program indicates that the Side member variable of the Square class was initialized with 0. This means that, like the regular variables, the member variables of a class are initialized by the compiler with default values that depend on the type of the variable. For example, a numeric member variable is initialized with 0 while a string-based variable is initialized with an empty string. After adding a member variable to a class, instead of relying on the default value assigned by the compiler, you can initialized it with a value of your choice, depending on the type of the variable. You have various alternatives. Imagine you want to write a (console-based) program for a department store and the customer has given you a preliminary catalog as follows:
Each item in this catalog is represented by its Stock number, its name or description, and its price. Based on this, you can create a class that represents each item.
Public Enum ItemCategory Women Men Girls Boys Babies Jewelry Beauty Bedroom Miscellaneous End Enum Public Class StoreItem Friend ItemNumber As Long Friend Category As ItemCategory Friend ItemName As String Friend UnitPrice As Double Public Sub ShowItem() Dim StrCategory As String
Select Case Category Case ItemCategory.Women StrCategory = "Women" Case ItemCategory.Men StrCategory = "Men" Case ItemCategory.Girls StrCategory = "Girls" Case ItemCategory.Boys StrCategory = "Boys" Case ItemCategory.Babies StrCategory = "Babies" Case ItemCategory.Jewelry StrCategory = "Jewelry" Case ItemCategory.Beauty StrCategory = "Beauty" Case ItemCategory.Bedroom StrCategory = "Bedroom" Case Else StrCategory = "Miscellaneous" End Select MsgBox("=-= Department Store =-=" & vbCrLf & _ "--- Store Inventory ---" & vbCrLf & _ "Item #:" & vbTab & vbTab & ItemNumber & vbCrLf & _ "Category:" & vbTab & StrCategory & vbCrLf & _ "Item Name:" & vbTab & ItemName & vbCrLf & _ "Unit Price:" & vbTab & FormatCurrency(UnitPrice), _ MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _ "Department Store") End Sub End Class 7. Save All
Notice that, this time, the default value assigned to the member variable applies. Instead of initializing a member variable when declaring it, you can create a method that would be used to do this. Here is an example: Public Class Square Private side As Double Public Sub SetSide() side = 48.25 End Sub End Class
Such a method can also be used to initialize more than one value. When you create a method used to initialize one or more member variables of a class, if you want the initialization to apply, you must make sure that you call that method first before calling other methods of the class. Just as you can create a method to initialize the member(s) of a class, you can overload that method with different versions to perform different initializations. Here are examples: Public Module Exercise Private Class Square Private side As Double Public Sub SetSide() side = 48.25 End Sub Public Sub SetSide(ByVal sd As Double) side = sd End Sub Function CalculatePerimeter() As Double Return Side * 4 End Function Function CalculateArea() As Double Return Side * Side End Function Public Sub Message() MsgBox("Square Characteristics" & vbCrLf & _ "Side:" & vbTab & vbTab & FormatNumber(Side) & vbCrLf & _ "Perimeter:" & vbTab & _ FormatNumber(CalculatePerimeter()) & vbCrLf & _ "Area:" & vbTab & vbTab & FormatNumber(CalculateArea())) End Sub End Class Public Function Main() As Integer Dim sqr As Square = New Square sqr.SetSide() sqr.Message() Dim sd As Double sd = CDbl(InputBox("Enter Square Side: ")) sqr.SetSide(sd) sqr.Message() Return 0 End Function End Module Here an example of running the program:
Notice that, although the Square.Side member variable is private, you cab call the SetSide() public method to initialize it before displaying the characteristics of a square.
Public Enum ItemCategory Women Men Girls Boys Babies Jewelry Beauty Bedroom Miscellaneous End Enum Public Class StoreItem Friend ItemNumber As Long Friend Category As ItemCategory Friend ItemName As String Friend UnitPrice As Double Public Sub Initialize(ByVal ByVal ByVal ByVal ItemNumber = Number Category = Type ItemName = Name UnitPrice = Price End Sub Number As Long, _ Type As ItemCategory, _ Name As String, _ Price As Double)
Public Sub ShowItem() Dim StrCategory As String Select Case Category Case ItemCategory.Women StrCategory = "Women" Case ItemCategory.Men StrCategory = "Men" Case ItemCategory.Girls StrCategory = "Girls" Case ItemCategory.Boys StrCategory = "Boys" Case ItemCategory.Babies StrCategory = "Babies" Case ItemCategory.Jewelry StrCategory = "Jewelry" Case ItemCategory.Beauty StrCategory = "Beauty" Case ItemCategory.Bedroom StrCategory = "Bedroom" Case Else StrCategory = "Miscellaneous" End Select MsgBox("=-= Department Store =-=" & vbCrLf & _ "--- Store Inventory ---" & vbCrLf & _ "Item #:" & vbTab & vbTab & ItemNumber & vbCrLf & _ "Category:" & vbTab & StrCategory & vbCrLf & _ "Item Name:" & vbTab & ItemName & vbCrLf & _ "Unit Price:" & vbTab & FormatCurrency(UnitPrice), _ MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _ "Department Store") End Sub End Class 2. Access the DepartmentStore.vb file 3. To use a StoreItem object, change the file as follows:
Public Module DepartmentStore Public Function Main() As Integer Dim Nbr As Long Dim Classification As ItemCategory Dim Description As String Dim Value As Double Dim Item As StoreItem Nbr = 608432 Classification = ItemCategory.Jewelry Description = "Silver 1/10-ct. T.W. Diamond Heart-Link Bracelet" Value = 95.85 Item = New StoreItem Item.Initialize(Nbr, Classification, Description, Value) Item.ShowItem() Return 0 End Function End Module 4. Execute the application to see the result
Class Construction
The Default Constructor
When you declare a variable of a class, a special method must be called to initialize the members of that class. This method is automatically provided for every class and it is called a constructor. Whenever you create a new class, a constructor is automatically provided to it. This particular constructor is called the default constructor. You have the option of creating it or not. Although a constructor is created for your class, you can customize its behavior or change it as you see fit. The constructor of a class is called New and it is created as a sub procedure. Here is an example: Public Class Square Public Sub New() End Sub End Class Like every method, a constructor is equipped with a body. In this body, you can access any of the member variables (or method(s)) of the same class. Consider the following program: Public Module Exercise Private Class Square Public Sub New() MsgBox("Square Builder") End Sub End Class Public Function Main() As Integer Dim sq As Square = New Square Return 0 End Function End Module When executed, it would produce:
This shows that, when a class has been instantiated, its constructor is the first method to be called. For this reason, you can use a constructor to initialize a class, that is, to assign default values to its member variables. Based on this, instead of initializing the member variable(s) of a class when initializing it or them, or instead of creating a special method used to initialize the member variable(s) of a class, you can use a constructor to do this. The advantage of a constructor is that it doesn't need to be called: it is automatically available whenever the class is instantiated.
Public Enum ItemCategory Women Men Girls Boys Babies Jewelry Beauty Bedroom Miscellaneous End Enum Public Class StoreItem Friend ItemNumber As Long Friend Category As ItemCategory Friend ItemName As String Friend UnitPrice As Double Public Sub New() Me.ItemNumber = 0 Me.Category = ItemCategory.Miscellaneous Me.ItemName = "Unknown" Me.UnitPrice = 0D End Sub Public Sub ShowItem() Dim StrCategory As String Select Case Category Case ItemCategory.Women StrCategory = "Women" Case ItemCategory.Men StrCategory = "Men" Case ItemCategory.Girls StrCategory = "Girls" Case ItemCategory.Boys StrCategory = "Boys" Case ItemCategory.Babies StrCategory = "Babies" Case ItemCategory.Jewelry StrCategory = "Jewelry" Case ItemCategory.Beauty StrCategory = "Beauty" Case ItemCategory.Bedroom StrCategory = "Bedroom" Case Else StrCategory = "Miscellaneous" End Select MsgBox("=-= Department Store =-=" & vbCrLf & _ "--- Store Inventory ---" & vbCrLf & _ "Item #:" & vbTab & vbTab & ItemNumber & vbCrLf & _ "Category:" & vbTab & StrCategory & vbCrLf & _ "Item Name:" & vbTab & ItemName & vbCrLf & _ "Unit Price:" & vbTab & FormatCurrency(UnitPrice), _ MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _ "Department Store") End Sub End Class 7. Access the DepartmentStore.vb file 8. To use a StoreItem object, change the file as follows:
Public Module DepartmentStore Public Function Main() As Integer Dim Item As StoreItem Item = New StoreItem Item.ShowItem() Return 0 End Function End Module 9. Execute the application to see the result
Public Enum ItemCategory Women Men Girls Boys Babies Jewelry Beauty Bedroom Miscellaneous End Enum Public Class StoreItem Friend ItemNumber As Long Friend Category As ItemCategory Friend ItemName As String Friend UnitPrice As Double Public Sub New(ByVal Number ByVal ByVal ByVal ItemNumber = Number Category = Type ItemName = Name UnitPrice = Price End Sub As Long, _ Type As ItemCategory, _ Name As String, _ Price As Double)
Case ItemCategory.Women StrCategory = "Women" Case ItemCategory.Men StrCategory = "Men" Case ItemCategory.Girls StrCategory = "Girls" Case ItemCategory.Boys StrCategory = "Boys" Case ItemCategory.Babies StrCategory = "Babies" Case ItemCategory.Jewelry StrCategory = "Jewelry" Case ItemCategory.Beauty StrCategory = "Beauty" Case ItemCategory.Bedroom StrCategory = "Bedroom" Case Else StrCategory = "Miscellaneous" End Select MsgBox("=-= Department Store =-=" & vbCrLf & _ "--- Store Inventory ---" & vbCrLf & _ "Item #:" & vbTab & vbTab & ItemNumber & vbCrLf & _ "Category:" & vbTab & StrCategory & vbCrLf & _ "Item Name:" & vbTab & ItemName & vbCrLf & _ "Unit Price:" & vbTab & FormatCurrency(UnitPrice), _ MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _ "Department Store") End Sub End Class 2. Access the DepartmentStore.vb file and change it as follows:
Public Module DepartmentStore Public Function Main() As Integer Dim Nbr As Long Dim Classification As ItemCategory Dim Description As String Dim Value As Double Dim Item As StoreItem Nbr = 759470 Classification = ItemCategory.Men Description = "Multistriped Organic Cotton Dress Shirt" Value = 35.5 Item = New StoreItem(Nbr, Classification, Description, Value) Item.ShowItem() Return 0 End Function End Module 3. Execute the application to see the result
Constructor Overloading
A constructor is the primary method of a class. It allows the programmer to initialize a variable of a class when the class is instantiated. A constructor that plays this role of initializing an instance of a class is also called an instance constructor. Most of the time, you don't need to create a constructor, since one is automatically provided to any class you create. Sometimes though, as we have seen in some classes, you need to create your own constructor as you judge it necessary and sometimes, a single constructor may not be sufficient. For example, when creating a class, you may decide, or find out, that there must be more than one way for a user to initialize a variable. Like any other method, a constructor can be overloaded. In other words, you can create a class and give it more than one constructor. The same rules used on overloading regular methods also apply to constructors: the different constructors must have different number of arguments or different types of arguments.
1. Access the StoreItem.vb file 2. To overload the constructor, change the file as follows:
Public Enum ItemCategory Women Men Girls Boys Babies Jewelry Beauty Bedroom Miscellaneous End Enum Public Class StoreItem Friend ItemNumber As Long Friend Category As ItemCategory Friend ItemName As String Friend ItemSize As String Friend UnitPrice As Double REM Default Constructor, used to initialize an unidentified object Public Sub New() Me.ItemNumber = 0 Me.Category = ItemCategory.Miscellaneous Me.ItemName = "Unknown" Me.ItemSize = "Unknown or Fits All" Me.UnitPrice = 0D End Sub REM This constructor is for items without size (jewelry, beauty, etc) Public Sub New(ByVal Number As Long, _ ByVal Type As ItemCategory, _ ByVal Name As String, _ ByVal Price As Double) Me.ItemNumber = Number Me.Category = Type Me.ItemName = Name Me.UnitPrice = Price End Sub REM This constructor is used to identify an item to wear Public Sub New(ByVal Number As Long, _ ByVal Type As ItemCategory, _ ByVal Name As String, _ ByVal Size As String, _ ByVal Price As Double) Me.ItemNumber = Number Me.Category = Type Me.ItemName = Name Me.ItemSize = Size Me.UnitPrice = Price End Sub REM This method is used to display a description of an item REM The caller will determine whether the item has a size or not Public Sub ShowItem(ByVal HasSize As Boolean) Dim StrCategory As String Select Case Category Case ItemCategory.Women StrCategory = "Women" Case ItemCategory.Men StrCategory = "Men" Case ItemCategory.Girls StrCategory = "Girls" Case ItemCategory.Boys StrCategory = "Boys" Case ItemCategory.Babies StrCategory = "Babies" Case ItemCategory.Jewelry StrCategory = "Jewelry" Case ItemCategory.Beauty StrCategory = "Beauty" Case ItemCategory.Bedroom StrCategory = "Bedroom" Case Else StrCategory = "Miscellaneous" End Select If HasSize = True Then MsgBox("=-= Department Store =-=" & vbCrLf & _ "--- Store Inventory ---" & vbCrLf & _ "Item #:" & vbTab & vbTab & ItemNumber & vbCrLf & "Category:" & vbTab & StrCategory & vbCrLf & _ "Item Name:" & vbTab & ItemName & vbCrLf & _ "Size:" & vbTab & vbTab & ItemSize & vbCrLf & _ "Unit Price:" & vbTab & FormatCurrency(UnitPrice), MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _ "Department Store") Else MsgBox("=-= Department Store =-=" & vbCrLf & _ "--- Store Inventory ---" & vbCrLf & _ "Item #:" & vbTab & vbTab & ItemNumber & vbCrLf & "Category:" & vbTab & StrCategory & vbCrLf & _ "Item Name:" & vbTab & ItemName & vbCrLf & _ "Unit Price:" & vbTab & FormatCurrency(UnitPrice),
_ _
MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _ "Department Store") End If End Sub End Class 3. Access the DepartmentStore.vb file and change it as follow:
Public Module DepartmentStore Public Function Main() As Integer Dim Nbr As Long Dim Classification As ItemCategory Dim Description As String Dim Size As String Dim Value As Double Dim Item As StoreItem REM Using the default constructor Item = New StoreItem Item.ShowItem(True) Nbr = 608432 Classification = ItemCategory.Jewelry Description = "Silver 1/10-ct. T.W. Diamond Heart-Link Bracelet" Value = 95.85 REM Using the constructor that takes 4 arguments Item = New StoreItem(Nbr, Classification, Description, Value) Item.ShowItem(False) Nbr = 437876 Classification = ItemCategory.Women Description = "Crinkled Georgette Dress" Size = "Medium" Value = 42.95 REM Using the constructor that takes 5 arguments REM after initialing a Women object Item = New StoreItem(Nbr, ItemCategory.Women, _ Description, Size, Value) Item.ShowItem(True) REM Using the constructor that takes 5 arguments REM Directly initialing the constructor Item = New StoreItem(790475, ItemCategory.Men, _ "New Wool Comfort Pants", "36x33", 38.75) Item.ShowItem(True) REM Using the constructor that takes 5 arguments REM Initialing the values in random order Item = New StoreItem(Type:=ItemCategory.Women, _ Size:="9 1/2 W", _ Price:=35.5, _ Name:="Modest Dress Heels", _ Number:=487046) Item.ShowItem(True) Return 0 End Function End Module 4. Execute the application to see the result:
Class Destruction
Garbage Collection
When you initialize a variable using the New operator, you are in fact asking the compiler to provide you some memory space in the heap memory. The compiler is said to "allocate" memory for your variable. When that variable is no longer needed, for example when your program closes, it (the variable) must be removed from memory and the space it was using can be made available to other variables or other programs. This is referred to as garbage collection. The .NET Framework solves the problem of garbage collection by letting the compiler "clean" memory after you. This is done automatically when the compiler judges it necessary so that the programmer doesn't need to worry about this issue.
Class Finalization
When you declare a variable based on a class, the compiler allocates memory for it. This portion of memory would be available and used while the program is running and as long as the compiler judges this necessary. While the program is running, the instance of the class uses or consumes the computer's resources as necessary. When the object is not needed anymore, for example when the program terminates, the object must be destroyed, the memory it was using must be emptied to be made available to other programs on the computer, and the resources that the object was using should (must) be freed to be restored to the computer so they can be used by other programs. To make this possible, the Object class is equipped with a method called Finalize that is protected and therefore made available to all descendant classes of the .NET Framework. The syntax of the Object.Finalize() method is: Overrides Protected Sub Finalize() The Finalize() method is automatically called when an instance of a class is not needed anymore. In all of the classes we have used so far, this method was transparently called when the compiler judged that the instance of the class was not used anymore. If you don't want this method to be called, call the Public Shared Sub SuppressFinalize(ByVal obj As Object) In most cases, you can let the compiler call the Finalize() method when the time comes.
Home
Next
Dim Diameter As Double Dim Circumference As Double circ = New Circle circ.Radius = 32.86 Diameter = circ.Radius * Circle.Twice Circumference = Diameter * circ.PI MsgBox("Circle Characteristics" & vbCrLf & _ "Radius:" & vbTab & vbTab & circ.Radius & vbCrLf & _ "Diameter:" & vbTab & vbTab & Diameter & vbCrLf & _ "Circumference:" & vbTab & Circumference) Return 0 End Function End Module This would produce:
If the value held by a read-only member variable is gotten from an expression, then the value should be initialized in the(a) construction with the desired expression. If you don't rightly initialize it, the compiler would initialize it with the default value based on the type of that variable. Therefore, you should make sure you initialize your ReadOnly member variables in a constructor, if those variables are based on an expression. Here are a few examples: Public Module Exercise Public Class Circle Public Radius As Double Public Const Twice As Integer = 2 Public ReadOnly PI As Double Public ReadOnly Diameter As Double Public ReadOnly Circumference As Double Public ReadOnly Area As Double Public Sub New() PI = 3.14159 Radius = 24.55 Diameter = Radius * Twice Circumference = Diameter * PI Area = Radius * Radius * PI End Sub End Class Public Function Main() As Integer Dim Circ As Circle = New Circle Circ.Radius = 32.86 MsgBox("Circle Characteristics" & vbCrLf & _ "Radius:" & vbTab & vbTab & Circ.Radius & vbCrLf & _ "Diameter:" & vbTab & vbTab & Circ.Diameter & vbCrLf & _ "Circumference:" & vbTab & Circ.Circumference & vbCrLf & _ "Area:" & vbTab & vbTab & Circ.Area) Return 0 End Function End Module This would produce:
In the previous section, we saw that a constant variable must be initialized when it is created. Although a read-only variable seems to follow the same rule, it doesn't. Remember that you don't need to initialize a read-only variable when you declare it since you can do this in the(a) constructor of the class. Also, because a constructor can be overloaded, a read-only member variable can hold different values depending on the particular constructor that is accessed at a particular time but the value of a constant variable cannot change: it is initialized once, in the class (or in a method) and it keeps that value throughout the class (or method).
A Class as a Field
Just like any of the variables we have used so far, you can make a class or a structure a member variable of another class. To use a class in your own class, of course you must have that class. You can use one of the classes already available in C# or you can first create your own class. Here is an example of a class: Public Class Point Friend x As Short Friend y As Short End Class A field is a member variable created from another class instead of a primitive type. To use one class as a member variable of another class, simply declare its variable as you would proceed with any of the member variables we have declared so far. Here is an example: Public Class Point Friend x As Short Friend y As Short End Class Public Class CoordinateSystem Private Start As Point End Class After a class has been declared as a member variable of another class, it can be used regularly. Because the member is a class, declared as a reference, there are some rules you must follow to use it. After declaring the member variable, you must make sure you have allocated memory for it. You must also make sure that the variable is initialized appropriately before it can be used; otherwise you would receive an error when compiling the program.
Public Class StoreItem Private nbr As Long Private cat As Char Private mk As String Private mdl As String Private price As Double Public Function GetItemNumber() As Long Return nbr End Function Public Sub SetItemNumber(ByVal number As Long) Me.nbr = number End Sub Public Function GetCategory() As String Select Case cat Case "a", "A" Return "Audio Cables" Case "b", "B" Return "Instructional and Tutorials (Books)" Case "c", "C" Return "Cell Phones and Accessories" Case "d", "D" Return "Bags and Cases" Case "e", "E" Return "Headphones" Case "f", "F" Return "Instructional and Tutorials (VHS & DVD)" Case "g", "G" Return "Digital Cameras" Case "h", "H" Return "Cables and Connectors" Case "i", "I" Return "PDAs and Accessories" Case "j", "J" Return "Telephones and Accessories" Case "k", "K" Return "Surge Protector" Case "l", "L" Return "TVs and Videos" Case Else Return "Unknown" End Select End Function Public Sub SetCategory(ByVal category As Char) Me.cat = category End Sub
Public Function GetMake() As String Return mk End Function Public Sub SetMake(ByVal make As String) Me.mk = make End Sub Public Function GetModel() As String Return mdl End Function Public Sub SetModel(ByVal model As String) Me.mdl = model End Sub Public Function GetUnitPrice() As Double Return price End Function Public Sub SetUnitPrice(ByVal unitPrice As Double) Me.price = unitPrice End Sub End Class 7. Save all
Pt.x = CShort(InputBox("Enter the x coordinate of the point: ")) Pt.y = CShort(InputBox("Enter the y coordinate of the point: ")) Return Pt End Function End Class Public Function Main() As Integer Dim Coordinate As Point Dim Coordinator As CoordinateSystem Coordinator = New CoordinateSystem Coordinate = Coordinator.GetThePoint() Return 0 End Function End Module
As done for the arguments of primitive types, you can pass more than one class as argument to a method. Because classes are always used as references, when passing a class as argument, it is implied to be passed by reference. To reinforce this, you can type the ByRef keyword to the left of the argument. Here are examples: Public Module Exercise Public Class Point Friend x As Short Friend y As Short End Class Public Class CoordinateSystem Private PtStart As Point Private PtEnd As Point Public Function GetThePoint() As Point Dim Pt As Point = New Point Pt.x = CShort(InputBox("Enter the x coordinate of the point: ")) Pt.y = CShort(InputBox("Enter the y coordinate of the point: ")) Return Pt End Function Public Sub ShowTheLine(ByRef StartPoint As Point, _ ByRef EndPoint As Point) MsgBox("Line Characteristics: The line goes from P(" & _ StartPoint.x & ", " & StartPoint.y & ") to Q(" & _ EndPoint.x & ", " & EndPoint.y & ")") End Sub End Class Public Function Main() As Integer Dim First, Second As Point Dim Coordinator As CoordinateSystem Coordinator = New CoordinateSystem First = Coordinator.GetThePoint() Second = Coordinator.GetThePoint() Coordinator.ShowTheLine(First, Second) Return 0 End Function End Module
Public Module ElectronicStore Dim DiscountAmount As Double Dim NetPrice As Double Dim Quantity As Integer Dim SaleTotal As Double Public Function GetDiscountRate() As Double Dim Discount As Double Discount = _ CDbl(InputBox("Discount Applied (Enter 0 to 100, 0 if no discount): ")) Return Discount End Function Public Function GetQuantity() As Integer Dim q As Integer q = CInt(inputbox("Enter Quantity: ")) Return q End Function Public Function Create() As StoreItem Dim ItemNumber As Long Dim Category As Char Dim Make As String Dim Model As String Dim Price As Double Dim SaleItem As StoreItem = New StoreItem ItemNumber = CLng(InputBox("Enter the Item #", "Nearson Electonics")) Category = CChar(InputBox("Category" & vbCrLf & _
"A - Audio Cables" & vbCrLf & _ "B - Instructional and Tutorials (Books)" & vbCrLf & _ "C - Cell Phones and Accessories" & vbCrLf & _ "D - Bags and Cases" & vbCrLf & _ "E - Headphones" & vbCrLf & _ "F - Instructional and Tutorials (VHS & DVD)" & vbCrLf & _ "G - Digital Cameras" & vbCrLf & _ "H - Cables and Connectors" & vbCrLf & _ "I - PDAs and Accessories" & vbCrLf & _ "J - Telephones and Accessories" & vbCrLf & _ "K - Surge Protector" & vbCrLf & _ "L - TVs and Videos" & vbCrLf & _ "Enter Your Choice:", "Nearson Electonics")) Make = InputBox("Enter Make", "Nearson Electonics") Model = InputBox("Enter Model", "Nearson Electonics") Price = CDbl(InputBox("Enter Unit Price:", "Nearson Electonics")) SaleItem.SetItemNumber(ItemNumber) SaleItem.SetCategory(Category) SaleItem.SetMake(Make) SaleItem.SetModel(Model) SaleItem.SetUnitPrice(Price) Return SaleItem End Function Public Sub ShowSaleItem(ByVal item As StoreItem) Dim discountRate As Double = GetDiscountRate() Quantity = CInt(GetQuantity()) DiscountAmount = item.GetUnitPrice() * discountRate / 100 NetPrice = item.GetUnitPrice() - DiscountAmount SaleTotal = NetPrice * Quantity MsgBox("=-= Nearson Electonics =-=" & vbCrLf & _ "Store Item Description" & vbCrLf & _ "Item Number:" & vbTab & item.GetItemNumber() & vbCrLf & _ "Category:" & vbTab & item.GetCategory() & vbCrLf & _ "Make:" & vbTab & vbTab & item.GetMake() & vbCrLf & _ "Model:" & vbTab & vbTab & item.GetModel() & vbCrLf & _ "Unit Price:" & vbTab & _ FormatCurrency(item.GetUnitPrice()) & vbCrLf & _ "Discount Rate:" & vbTab & _ FormatPercent(discountRate / 100) & vbCrLf & _ "Discount Amount:" & vbTab & _ FormatCurrency(DiscountAmount) & vbCrLf & _ "Price/Item:" & vbTab & FormatCurrency(NetPrice) & vbCrLf & _ "Quantity: " & vbTab & Quantity & vbCrLf & _ "Sale Total: " & vbTab & FormatCurrency(SaleTotal), _ MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _ "Nearson Electonics") End Sub Public Function Main() As Integer Dim Item As StoreItem = New StoreItem() Item = Create() ShowSaleItem(Item) End Function End Module 2. Execute the application to test it 3. Enter the item information as follows: Item # Category Make Model Unit Price Discount 917305 e Sennheiser HD280 Pro Closed-Back Headphones 99.95 20
Quantity
Me.x = Same.x Me.y = Same.y End Sub End Class Public Sub ShowPoint(ByVal Coord As Point) MsgBox("Point Coordinate: P(" & Coord.x & ", " & Coord.y & ")") End Sub Public Function Main() As Integer Dim Pt As Point = New Point Pt.x = 4 Pt.y = 6 ShowPoint(Pt) Dim One As Point = New Point One.Equivalent(Pt) ShowPoint(One) Return 0 End Function End Module This would produce:
Instead of first declaring a variable of the class and initializing it, you can create an instance of the class in the parentheses of the calling method. To do this, you may need a constructor that can specify the values of the fields of the class so the argument can be rightfully initialized. Here is an example: Public Module Exercise Public Class Point Friend x As Integer Friend y As Integer Public Sub New() End Sub Public Sub New(ByVal XCoord As Integer, ByVal YCoord As Integer) Me.x = XCoord Me.y = YCoord End Sub Public Sub Equivalent(ByVal Same As Point) Me.x = Same.x Me.y = Same.y End Sub End Class Public Sub ShowPoint(ByVal Coord As Point) MsgBox("Point Coordinate: P(" & Coord.x & ", " & Coord.y & ")") End Sub Public Function Main() As Integer Dim Pt As Point = New Point Pt.x = 4 Pt.y = 6 ShowPoint(Pt) Dim One As Point = New Point One.Equivalent(New Point(-3, 2)) ShowPoint(One) Return 0 End Function End Module This would produce:
Instead of a formal method, you can use a constructor of the class to pass an instance of the same class. Then, in the constructor, use the argument as you see fit, knowing that all the members of the class are available. Here is an example: Public Class Point Friend x As Integer Friend y As Integer Public Sub New() End Sub Public Sub New(ByVal XCoord As Integer, ByVal YCoord As Integer) Me.x = XCoord Me.y = YCoord End Sub Public Sub New(ByVal Same As Point) Me.x = Same.x Me.y = Same.y End Sub End Class Obviously the purpose of passing a class to one of its own methods is not to find its equivalent. The C# language (actually the .NET Framework) can also take care of that (through the Equals() built-in method). Instead, you can create a method that takes an instance of the same class but modifies that instance. For example, for our Point class, we may want to create a new point that is distanced by one unit from the current Point object. Here is an example of doing that: Public Module Exercise Public Class Point Friend x As Integer Friend y As Integer Public Sub New() End Sub Public Sub New(ByVal XCoord As Integer, ByVal YCoord As Integer) Me.x = XCoord Me.y = YCoord End Sub Public Sub Equivalent(ByVal Same As Point) Me.x = Same.x Me.y = Same.y End Sub Public Sub CreatePointOneUnitAway(ByVal AddUnit As Point) Me.x = AddUnit.x + 1 Me.y = AddUnit.y + 1 End Sub End Class Public Sub ShowPoint(ByVal Coord As Point) MsgBox("Point Coordinate: P(" & Coord.x & ", " & Coord.y & ")") End Sub Public Function Main() As Integer Dim Pt As Point = New Point Pt.x = 4 Pt.y = 6 Dim One As Point = New Point One.CreatePointOneUnitAway(Pt) ShowPoint(One) One.CreatePointOneUnitAway(New Point(-8, -3)) ShowPoint(One) Return 0 End Function End Module This would produce:
Alternatively, you can declare an instance of the class, use the current values of the class combined with the those of the instance to get new values, and then return the instance. Remember that, to call a method, if it is not static, you will need to declare an instance of the class from where you are calling the method. The second type of implementation consists of modifying the instance of the class that is calling the method. For example, you can add values to its fields or you can perform any other operation you want on the members of the calling instance. is an example:
Public Module Exercise Public Class Point Friend x As Integer Friend y As Integer Public Sub New() End Sub Public Sub New(ByVal XCoord As Integer, ByVal YCoord As Integer) Me.x = XCoord Me.y = YCoord End Sub Public Sub New(ByVal Same As Point) Me.x = Same.x Me.x = Same.x End Sub REM This method adds 1 to each field of the class REM to get a new point away North-East of the current point Public Function CreatePointOneUnitAway() As Point Me.x = Me.x + 1 Me.y = Me.y + 1 Return Me End Function End Class Public Sub ShowPoint(ByVal Coord As Point) MsgBox("Point Coordinate: P(" & Coord.x & ", " & Coord.y & ")") End Sub Public Function Main() As Integer Dim Pt As Point = New Point Pt.x = 4 Pt.y = 6 ShowPoint(Pt) Dim One As Point = New Point(-8, 5) Dim Another As Point = One.CreatePointOneUnitAway() ShowPoint(Another) Return 0 End Function End Module This would produce:
As we have learned now, you can create a method that takes an argument that is the same type as its parent class. In the method, you can access any member of the class, including calling the other methods of the class.
Home
In order to access the member variables of the above Rectangle class, you must declare a variable of the class. The Visual Basic language provides an alternative. You can declare a member variable so that you can access it from anywhere in your code without primarily declaring a variable of the class. In order to have such a member variable, you must explicitly create it as shared. To create a shared member variable, type the Shared keyword on its left when declaring it. After the shared member variable has been declared, you can use it like any other member variable of
that class, except that you don't need to declare an instance of that class when you want to access that member variable. Here is an example: Public Module Exercise Friend Class Rectangle Public Length As Double Public Shared Height As Double Public Function CalculatePerimeter#() Return (Length + Height) * 2 End Function Public Function CalcaulteArea#() Return Length * Height End Function End Class Public Function Main() As Integer REM Notice that a Rectangle variable is not declared Rectangle.Height = 20.68 MsgBox("Rectangle Characteristics" & vbCrLf & _ "Height:" & vbTab & vbTab & Rectangle.Height) Return 0 End Function End Module This would produce:
Based on this, when creating a class, you will decide whether you want a particular member variable to be shared or not. You can have only one, two, more, or all member variables shared in a class. Experience and your own goal will guide you.
Shared Methods
Consider the following class: Public Module Exercise Friend Class Rectangle Public Shared Length As Double Public Shared Height As Double Public Function CalculatePerimeter#() Return (Length + Height) * 2 End Function Public Function CalcaulteArea#() Return Length * Height End Function End Class Public Function Main() As Integer REM Notice that a Rectangle variable is not declared Rectangle.Height = 20.68 Rectangle.Length = 32.47 MsgBox("Rectangle Characteristics" & vbCrLf & _ "Length:" & vbTab & Rectangle.Length & vbCrLf & _ "Height:" & vbTab & Rectangle.Height) Return 0 End Function End Module This would produce:
Like member variables, a method can be shared among classes. In some cases, shared methods are more used than shared member variables because a shared method allows performing an action on a class without declaring an instance of that class. To create a shared method, type the Shared keyword on the left of the Sub or the Function keyword. Here is an example:
Here is an example: Friend Class Rectangle Shared Function CalculatePerimeter#() Return (Length + Height) * 2 End Function End Class You can apply the access modifier on the method as we have done so far. Here are examples: Friend Class Rectangle Public Shared Function CalculatePerimeter#() End Function Public Shared Function CalcaulteArea#() End Function End Class Like a shared member variable, once a method has been created as shared, it can be accessed directly from anywhere. Remember that you would need to type the name of the class before accessing the method. The name of the class allows you to "qualify" the method. Here is an example: Public Module Exercise Friend Class Rectangle Public Shared Length As Double Public Shared Height As Double Public Shared Function CalculatePerimeter#() Return (Length + Height) * 2 End Function Public Shared Function CalcaulteArea#() Return Length * Height End Function End Class Public Function Main() As Integer REM Notice that a Rectangle variable is not declared Rectangle.Height = 20.68 Rectangle.Length = 32.47 MsgBox("Rectangle Characteristics" & vbCrLf & _ "Length:" & vbTab & vbTab & Rectangle.Length & vbCrLf & _ "Height:" & vbTab & vbTab & Rectangle.Height & vbCrLf & _ "Perimeter: " & vbTab & Rectangle.CalculatePerimeter#() & vbCrLf & _ "Area: " & vbTab & vbTab & Rectangle.CalcaulteArea#()) Return 0 End Function End Module
Home
Dim Diameter As Double Dim Circumference As Double circ = New Circle circ.Radius = 32.86 Diameter = circ.Radius * Circle.Twice Circumference = Diameter * circ.PI MsgBox("Circle Characteristics" & vbCrLf & _ "Radius:" & vbTab & vbTab & circ.Radius & vbCrLf & _ "Diameter:" & vbTab & vbTab & Diameter & vbCrLf & _ "Circumference:" & vbTab & Circumference) Return 0 End Function End Module This would produce:
If the value held by a read-only member variable is gotten from an expression, then the value should be initialized in the(a) construction with the desired expression. If you don't rightly initialize it, the compiler would initialize it with the default value based on the type of that variable. Therefore, you should make sure you initialize your ReadOnly member variables in a constructor, if those variables are based on an expression. Here are a few examples: Public Module Exercise Public Class Circle Public Radius As Double Public Const Twice As Integer = 2 Public ReadOnly PI As Double Public ReadOnly Diameter As Double Public ReadOnly Circumference As Double Public ReadOnly Area As Double Public Sub New() PI = 3.14159 Radius = 24.55 Diameter = Radius * Twice Circumference = Diameter * PI Area = Radius * Radius * PI End Sub End Class Public Function Main() As Integer Dim Circ As Circle = New Circle Circ.Radius = 32.86 MsgBox("Circle Characteristics" & vbCrLf & _ "Radius:" & vbTab & vbTab & Circ.Radius & vbCrLf & _ "Diameter:" & vbTab & vbTab & Circ.Diameter & vbCrLf & _ "Circumference:" & vbTab & Circ.Circumference & vbCrLf & _ "Area:" & vbTab & vbTab & Circ.Area) Return 0 End Function End Module This would produce:
In the previous section, we saw that a constant variable must be initialized when it is created. Although a read-only variable seems to follow the same rule, it doesn't. Remember that you don't need to initialize a read-only variable when you declare it since you can do this in the(a) constructor of the class. Also, because a constructor can be overloaded, a read-only member variable can hold different values depending on the particular constructor that is accessed at a particular time but the value of a constant variable cannot change: it is initialized once, in the class (or in a method) and it keeps that value throughout the class (or method).
A Class as a Field
Just like any of the variables we have used so far, you can make a class or a structure a member variable of another class. To use a class in your own class, of course you must have that class. You can use one of the classes already available in C# or you can first create your own class. Here is an example of a class: Public Class Point Friend x As Short Friend y As Short End Class A field is a member variable created from another class instead of a primitive type. To use one class as a member variable of another class, simply declare its variable as you would proceed with any of the member variables we have declared so far. Here is an example: Public Class Point Friend x As Short Friend y As Short End Class Public Class CoordinateSystem Private Start As Point End Class After a class has been declared as a member variable of another class, it can be used regularly. Because the member is a class, declared as a reference, there are some rules you must follow to use it. After declaring the member variable, you must make sure you have allocated memory for it. You must also make sure that the variable is initialized appropriately before it can be used; otherwise you would receive an error when compiling the program.
Public Class StoreItem Private nbr As Long Private cat As Char Private mk As String Private mdl As String Private price As Double Public Function GetItemNumber() As Long Return nbr End Function Public Sub SetItemNumber(ByVal number As Long) Me.nbr = number End Sub Public Function GetCategory() As String Select Case cat Case "a", "A" Return "Audio Cables" Case "b", "B" Return "Instructional and Tutorials (Books)" Case "c", "C" Return "Cell Phones and Accessories" Case "d", "D" Return "Bags and Cases" Case "e", "E" Return "Headphones" Case "f", "F" Return "Instructional and Tutorials (VHS & DVD)" Case "g", "G" Return "Digital Cameras" Case "h", "H" Return "Cables and Connectors" Case "i", "I" Return "PDAs and Accessories" Case "j", "J" Return "Telephones and Accessories" Case "k", "K" Return "Surge Protector" Case "l", "L" Return "TVs and Videos" Case Else Return "Unknown" End Select End Function Public Sub SetCategory(ByVal category As Char) Me.cat = category End Sub
Public Function GetMake() As String Return mk End Function Public Sub SetMake(ByVal make As String) Me.mk = make End Sub Public Function GetModel() As String Return mdl End Function Public Sub SetModel(ByVal model As String) Me.mdl = model End Sub Public Function GetUnitPrice() As Double Return price End Function Public Sub SetUnitPrice(ByVal unitPrice As Double) Me.price = unitPrice End Sub End Class 7. Save all
Pt.x = CShort(InputBox("Enter the x coordinate of the point: ")) Pt.y = CShort(InputBox("Enter the y coordinate of the point: ")) Return Pt End Function End Class Public Function Main() As Integer Dim Coordinate As Point Dim Coordinator As CoordinateSystem Coordinator = New CoordinateSystem Coordinate = Coordinator.GetThePoint() Return 0 End Function End Module
As done for the arguments of primitive types, you can pass more than one class as argument to a method. Because classes are always used as references, when passing a class as argument, it is implied to be passed by reference. To reinforce this, you can type the ByRef keyword to the left of the argument. Here are examples: Public Module Exercise Public Class Point Friend x As Short Friend y As Short End Class Public Class CoordinateSystem Private PtStart As Point Private PtEnd As Point Public Function GetThePoint() As Point Dim Pt As Point = New Point Pt.x = CShort(InputBox("Enter the x coordinate of the point: ")) Pt.y = CShort(InputBox("Enter the y coordinate of the point: ")) Return Pt End Function Public Sub ShowTheLine(ByRef StartPoint As Point, _ ByRef EndPoint As Point) MsgBox("Line Characteristics: The line goes from P(" & _ StartPoint.x & ", " & StartPoint.y & ") to Q(" & _ EndPoint.x & ", " & EndPoint.y & ")") End Sub End Class Public Function Main() As Integer Dim First, Second As Point Dim Coordinator As CoordinateSystem Coordinator = New CoordinateSystem First = Coordinator.GetThePoint() Second = Coordinator.GetThePoint() Coordinator.ShowTheLine(First, Second) Return 0 End Function End Module
Public Module ElectronicStore Dim DiscountAmount As Double Dim NetPrice As Double Dim Quantity As Integer Dim SaleTotal As Double Public Function GetDiscountRate() As Double Dim Discount As Double Discount = _ CDbl(InputBox("Discount Applied (Enter 0 to 100, 0 if no discount): ")) Return Discount End Function Public Function GetQuantity() As Integer Dim q As Integer q = CInt(inputbox("Enter Quantity: ")) Return q End Function Public Function Create() As StoreItem Dim ItemNumber As Long Dim Category As Char Dim Make As String Dim Model As String Dim Price As Double Dim SaleItem As StoreItem = New StoreItem ItemNumber = CLng(InputBox("Enter the Item #", "Nearson Electonics")) Category = CChar(InputBox("Category" & vbCrLf & _
"A - Audio Cables" & vbCrLf & _ "B - Instructional and Tutorials (Books)" & vbCrLf & _ "C - Cell Phones and Accessories" & vbCrLf & _ "D - Bags and Cases" & vbCrLf & _ "E - Headphones" & vbCrLf & _ "F - Instructional and Tutorials (VHS & DVD)" & vbCrLf & _ "G - Digital Cameras" & vbCrLf & _ "H - Cables and Connectors" & vbCrLf & _ "I - PDAs and Accessories" & vbCrLf & _ "J - Telephones and Accessories" & vbCrLf & _ "K - Surge Protector" & vbCrLf & _ "L - TVs and Videos" & vbCrLf & _ "Enter Your Choice:", "Nearson Electonics")) Make = InputBox("Enter Make", "Nearson Electonics") Model = InputBox("Enter Model", "Nearson Electonics") Price = CDbl(InputBox("Enter Unit Price:", "Nearson Electonics")) SaleItem.SetItemNumber(ItemNumber) SaleItem.SetCategory(Category) SaleItem.SetMake(Make) SaleItem.SetModel(Model) SaleItem.SetUnitPrice(Price) Return SaleItem End Function Public Sub ShowSaleItem(ByVal item As StoreItem) Dim discountRate As Double = GetDiscountRate() Quantity = CInt(GetQuantity()) DiscountAmount = item.GetUnitPrice() * discountRate / 100 NetPrice = item.GetUnitPrice() - DiscountAmount SaleTotal = NetPrice * Quantity MsgBox("=-= Nearson Electonics =-=" & vbCrLf & _ "Store Item Description" & vbCrLf & _ "Item Number:" & vbTab & item.GetItemNumber() & vbCrLf & _ "Category:" & vbTab & item.GetCategory() & vbCrLf & _ "Make:" & vbTab & vbTab & item.GetMake() & vbCrLf & _ "Model:" & vbTab & vbTab & item.GetModel() & vbCrLf & _ "Unit Price:" & vbTab & _ FormatCurrency(item.GetUnitPrice()) & vbCrLf & _ "Discount Rate:" & vbTab & _ FormatPercent(discountRate / 100) & vbCrLf & _ "Discount Amount:" & vbTab & _ FormatCurrency(DiscountAmount) & vbCrLf & _ "Price/Item:" & vbTab & FormatCurrency(NetPrice) & vbCrLf & _ "Quantity: " & vbTab & Quantity & vbCrLf & _ "Sale Total: " & vbTab & FormatCurrency(SaleTotal), _ MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _ "Nearson Electonics") End Sub Public Function Main() As Integer Dim Item As StoreItem = New StoreItem() Item = Create() ShowSaleItem(Item) End Function End Module 2. Execute the application to test it 3. Enter the item information as follows: Item # Category Make Model Unit Price Discount 917305 e Sennheiser HD280 Pro Closed-Back Headphones 99.95 20
Quantity
Me.x = Same.x Me.y = Same.y End Sub End Class Public Sub ShowPoint(ByVal Coord As Point) MsgBox("Point Coordinate: P(" & Coord.x & ", " & Coord.y & ")") End Sub Public Function Main() As Integer Dim Pt As Point = New Point Pt.x = 4 Pt.y = 6 ShowPoint(Pt) Dim One As Point = New Point One.Equivalent(Pt) ShowPoint(One) Return 0 End Function End Module This would produce:
Instead of first declaring a variable of the class and initializing it, you can create an instance of the class in the parentheses of the calling method. To do this, you may need a constructor that can specify the values of the fields of the class so the argument can be rightfully initialized. Here is an example: Public Module Exercise Public Class Point Friend x As Integer Friend y As Integer Public Sub New() End Sub Public Sub New(ByVal XCoord As Integer, ByVal YCoord As Integer) Me.x = XCoord Me.y = YCoord End Sub Public Sub Equivalent(ByVal Same As Point) Me.x = Same.x Me.y = Same.y End Sub End Class Public Sub ShowPoint(ByVal Coord As Point) MsgBox("Point Coordinate: P(" & Coord.x & ", " & Coord.y & ")") End Sub Public Function Main() As Integer Dim Pt As Point = New Point Pt.x = 4 Pt.y = 6 ShowPoint(Pt) Dim One As Point = New Point One.Equivalent(New Point(-3, 2)) ShowPoint(One) Return 0 End Function End Module This would produce:
Instead of a formal method, you can use a constructor of the class to pass an instance of the same class. Then, in the constructor, use the argument as you see fit, knowing that all the members of the class are available. Here is an example: Public Class Point Friend x As Integer Friend y As Integer Public Sub New() End Sub Public Sub New(ByVal XCoord As Integer, ByVal YCoord As Integer) Me.x = XCoord Me.y = YCoord End Sub Public Sub New(ByVal Same As Point) Me.x = Same.x Me.y = Same.y End Sub End Class Obviously the purpose of passing a class to one of its own methods is not to find its equivalent. The C# language (actually the .NET Framework) can also take care of that (through the Equals() built-in method). Instead, you can create a method that takes an instance of the same class but modifies that instance. For example, for our Point class, we may want to create a new point that is distanced by one unit from the current Point object. Here is an example of doing that: Public Module Exercise Public Class Point Friend x As Integer Friend y As Integer Public Sub New() End Sub Public Sub New(ByVal XCoord As Integer, ByVal YCoord As Integer) Me.x = XCoord Me.y = YCoord End Sub Public Sub Equivalent(ByVal Same As Point) Me.x = Same.x Me.y = Same.y End Sub Public Sub CreatePointOneUnitAway(ByVal AddUnit As Point) Me.x = AddUnit.x + 1 Me.y = AddUnit.y + 1 End Sub End Class Public Sub ShowPoint(ByVal Coord As Point) MsgBox("Point Coordinate: P(" & Coord.x & ", " & Coord.y & ")") End Sub Public Function Main() As Integer Dim Pt As Point = New Point Pt.x = 4 Pt.y = 6 Dim One As Point = New Point One.CreatePointOneUnitAway(Pt) ShowPoint(One) One.CreatePointOneUnitAway(New Point(-8, -3)) ShowPoint(One) Return 0 End Function End Module This would produce:
Alternatively, you can declare an instance of the class, use the current values of the class combined with the those of the instance to get new values, and then return the instance. Remember that, to call a method, if it is not static, you will need to declare an instance of the class from where you are calling the method. The second type of implementation consists of modifying the instance of the class that is calling the method. For example, you can add values to its fields or you can perform any other operation you want on the members of the calling instance. is an example:
Public Module Exercise Public Class Point Friend x As Integer Friend y As Integer Public Sub New() End Sub Public Sub New(ByVal XCoord As Integer, ByVal YCoord As Integer) Me.x = XCoord Me.y = YCoord End Sub Public Sub New(ByVal Same As Point) Me.x = Same.x Me.x = Same.x End Sub REM This method adds 1 to each field of the class REM to get a new point away North-East of the current point Public Function CreatePointOneUnitAway() As Point Me.x = Me.x + 1 Me.y = Me.y + 1 Return Me End Function End Class Public Sub ShowPoint(ByVal Coord As Point) MsgBox("Point Coordinate: P(" & Coord.x & ", " & Coord.y & ")") End Sub Public Function Main() As Integer Dim Pt As Point = New Point Pt.x = 4 Pt.y = 6 ShowPoint(Pt) Dim One As Point = New Point(-8, 5) Dim Another As Point = One.CreatePointOneUnitAway() ShowPoint(Another) Return 0 End Function End Module This would produce:
As we have learned now, you can create a method that takes an argument that is the same type as its parent class. In the method, you can access any member of the class, including calling the other methods of the class.
Home
Nesting a Class
Description
A class can be created inside of another class. A class created inside of another is referred to as nested. To nest a class, simply create it as you would any other. Here is an example of a class called Inside that is nested in a class called Outside: Public Class Outside Public Class Inside End Class End Class In the same way, you can nest as many classes as you wish in another class and you can nest as many classes inside of other nested classes if you judge it necessary. Just as you would manage any other class so can you exercise control on a nested class. For example, you can declare all necessary fields, properties, or methods in the nested class or in the nesting class. When you create one class inside of another, there is no special programmatic relationship between both classes: just because a class is nested does not mean that the nested class has immediate access to the members of the nesting class. They are two different classes and they can be used separately as you judge it necessary. The name of a nested class outside of the nesting class, use it. For example, if you outside of Outside, you must is not "visible" outside of the nesting class. To access a nested class you must qualify the name of the nested class anywhere you want to want to declare an Inside variable somewhere in the program but qualify its name. Here is an example:
Public Module Exercise Public Class Outside Public Class Inside Public Sub New() MsgBox(" =- Inside -=") End Sub End Class Public Sub New() MsgBox(" -= Outside =-") End Sub End Class Public Function Main() As Integer Dim Out As Outside = New Outside Dim Ins As Outside.Inside = New Outside.Inside Return 0 End Function End Module This would produce:
Because there is no programmatically privileged relationship between a nested class and its "container" class, if you want to access the nested class in the nesting class, you can use its static members. In other words, if you want, you can declare static all members of the nested class that you want to access in the nesting class. Here is an example: Public Module Exercise Public Class Outside Public Class Inside Public Shared InMessage As String Public Sub New() MsgBox("=- Insider -=") InMessage = "Sitting inside while it's raining" End Sub
Public Shared Sub Show() msgbox("Show me the wonderful world of C# Programming") End Sub End Class Public Sub New() MsgBox("-= Outside =-") End Sub Public Sub Display() msgbox(Inside.InMessage) Inside.Show() End Sub End Class Public Function Main() As Integer Dim Recto As Outside = New Outside Dim Ins As Outside.Inside = New Outside.Inside Recto.Display() Return 0 End Function End Module In the same way, if you want to access the nesting class in the nested class, you can go through the static members of the nesting class. To do this, you can declare static all members of the nesting class that you want to access in the nested class. Here is an example: Public Module Exercise Public Class Outside Public Class Inside Public Shared InMessage As String Public Sub New() MsgBox("=- Insider -=") InMessage = "Sitting inside while it's raining" End Sub Public Shared Sub Show() msgbox("Show me the wonderful world of C# Programming") End Sub Public Sub FieldFromOutside() msgbox(Outside.OutMessage) End Sub End Class Private Shared OutMessage As String Public Sub New() MsgBox(" -= The Parent =-") OutMessage = "Standing outside! It's cold and raining!!" End Sub Public Sub Display() MsgBox(Inside.InMessage) Inside.Show() End Sub End Class Public Function Main() As Integer Dim Recto As Outside = New Outside Dim Ins As Outside.Inside = New Outside.Inside Recto.Display() Ins.FieldFromOutside() Return 0 End Function End Module This would produce:
Instead of static members, if you want to access members of a nested class in the nesting class, you can first declare a variable of the nested class in the nesting class. In the same way, if you want to access members of a nesting class in the nested class, you can first declare a variable of the nesting class in the nested class. Here is an example:
Public Module Exercise Public Class Outside REM A member of the nesting class Private OutMessage As String REM The nested class Public Class Inside REM A field in the nested class Public InMessage As String REM A constructor of the nested class Public Sub New() MsgBox("=- Insider -=") Me.InMessage = "Sitting inside while it's raining" End Sub REM A method of the nested class Public Sub Show() REM Declare a variable to access the nesting class Dim Outsider As Outside = New Outside MsgBox(outsider.OutMessage) End Sub End Class REM End of the nested class REM A constructor of the nesting class Public Sub New() Me.OutMessage = "Standing outside! It's cold and raining!!" MsgBox("-= The Parent =-") End Sub REM A method of the nesting class Public Sub Display() MsgBox(insider.InMessage) End Sub REM Declare a variable to access the nested class Dim insider As Inside = New Inside End Class Public Function Main() As Integer Dim Recto As Outside = New Outside Dim Ins As Outside.Inside = New Outside.Inside Ins.Show() Recto.Display() Return 0 End Function End Module This would produce:
Previous
Next
Module Exercise Public Function Main() As Integer Dim circ As Circle = New Circle circ.rad = 25.84 Console.WriteLine(" -=- Circle Characteristics -=-") Console.WriteLine("Radius: {0}", circ.rad) Return 0 End Function End Module When you create the member variables of a class or of a structure, such as the above Radius of the Circle class, it is a good idea not to directly expose them to other parts of the program so that those other parts would not be able to easily change the values of the members and retrieve their values anyhow. This technique makes sure that a member variable is not accessed outside the class (or structure) so that the clients of the class (or structure) cannot directly influence the value of the member variable. To avoid this type of access, you can make the member variable(s) private. This would transform the above Circle class to the following: Public Class Circle Private rad As Double End Class If you create a member variable as private but still want other classes (or structures) or procedures to access or get the value of such a member variable, you should then provide a means for members of the class to access that private member.
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
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
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
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
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
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
11. To create the library, in the Solution Explorer, right-click Mathematics and click Build 12. To create a new project, on the main menu, click File -> New Project... 13. In the middle list, click Console Application 14. Change the name to Algebra1 15. Click OK 16. On the main menu, click Project -> Algebra1 Properties 17. Click the arrow of the Application Type box and select Windows Forms Application 18. In the Solution Explorer, right-click Module1.vb and click Rename 19. Type Algebra.vb and press Enter twice 20. Change the document as follows: Module Algebra Public Function Main() As Integer Return 0 End Function End Module 21. In the Solution Explorer, right-click Algebra1 and click Add Reference... 22. Click the Browse tab 23. Locate the folder where the Mathematics library was created 24. Select Mathematics.dll 25. Click OK 26. To create a new class, in the Class View, right-click Algebra1 -> Add -> Class... 27. Set the Name to Rational 28. Click Add 29. Change the file as follows: Imports Mathematics Public Class Rational Private Num As Long Private Den As Long Public Sub New(ByVal n As Long, ByVal d As Long) Num = n Den = d End Sub Public Property Numerator() As String Get Return Num / Arithmetic.GreatestCommonDivisor(Num, Den) End Get Set(ByVal value As String) Num = value End Set End Property Public Property Denominator() As String Get Return Den / Arithmetic.GreatestCommonDivisor(Num, Den) End Get Set(ByVal value As String) Den = value End Set End Property Public Overrides Function ToString() As String Dim Numer As Long Dim Denom As Long Numer = Num / Arithmetic.GreatestCommonDivisor(Num, Den) Denom = Den / Arithmetic.GreatestCommonDivisor(Num, Den) If Denom = 1 Then Return Numer.ToString() Else Return String.Format("{0}/{1}", Numer, Denom) End If End Function End Class
The Formula
To overload an operator, you must create a Shared method using the following formula: [ <attrlist> ] Public [ Overloads ] Shared [ Shadows ] [ Widening | Narrowing ] Operator operatorsymbol ( operand1 [, operand2 ]) [ As [ <attrlist> ] type ] [ statements ] [ statements ]
Return returnvalue [ statements ] End Operator You can start with the Public access modifier, followed by the Shared keyword. You can use additional keywords and/or mechanisms to control access to the method. You must then use the Operator keyword. This is followed by the actual operator you want to customize. There are rules you must, and suggestions you should, follow: Not all operators need to be customized for all classes. For example, while it would be feasible to add two books to get a new book that includes all the pages on both books and their combined authors, it may not be realistic to multiply two books (to get what?). Therefore, you should select the right operator based on your needs While some operators are always available to be overloaded, some operators have restrictive rules. This means that you cannot just use any operator anyhow Not all operators are overloadable After the operator, open that parentheses that must always be used on a function. In the parentheses, you will add one or more arguments, depending on the operator. After the closing parenthesis, you must specify a return type. Normally, you should return the class itself. After all, the operator will act on an object of its class type. For this reason, the method should return a value that represents its class. To end the method, you must use the End Operator expression. In the body of the method, you can implement the behavior and make sure you return a value. After defining the method, you can call it either inside or outside the class.
Overloading an Operator
Unary Operators
A unary operator is one that acts on one value. The Visual Basic language provides many unary operators but not all can be overloaded. The unary operarors available for overloading are +, -, Not, IsTrue, IsFalse, and CType. To overload a unary operator, pass one argument to the parentheses of the method. In the body of the method, perform the desired operation. Here is an example of overloading a unary operator: Public Class Natural Public Number As Integer Public Sub New(ByVal N As Integer) Number = N End Sub Public Shared Operator Not(ByVal Value As Natural) As Natural Dim Nbr As Integer = Value.Number Dim N As Integer = Not Nbr Dim Nat As Natural = New Natural(N) Return Nat End Operator Public Overrides Function ToString() As String Return Number.ToString() End Function End Class Here is an example of applying that operator: Public Module Exercise Public Function Main() As Integer Dim Nbr As Natural Nbr = New Natural(1405) MsgBox("The bitwise nagation of " & Nbr.ToString() & " is " & (Not Nbr).ToString()) Return 0 End Function End Module This would produce:
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.
1. Access the Rational.vb file and change it as follows: Imports Mathematics Public Class Rational Private Num As Long Private Den As Long Public Sub New(ByVal n As Long, ByVal d As Long) Num = n Den = d End Sub Public Property Numerator() As String Get Return Num / Arithmetic.GreatestCommonDivisor(Num, Den) End Get Set(ByVal value As String) Num = value End Set End Property Public Property Denominator() As String Get Return Den / Arithmetic.GreatestCommonDivisor(Num, Den) End Get Set(ByVal value As String) Den = value End Set End Property Public Shared Operator +(ByVal First As Rational, ByVal Second As Rational) As Rational Dim Top As Long Dim Bottom As Long Top = (First.Numerator * Second.Denominator) + (First.Denominator * Second.Numerator) Bottom = First.Denominator * Second.Denominator Return New Rational(Top, Bottom) End Operator Public Shared Operator -(ByVal First As Rational, ByVal Second As Rational) As Rational Dim Top As Long Dim Bottom As Long Top = (First.Numerator * Second.Denominator) (First.Denominator * Second.Numerator) Bottom = First.Denominator * Second.Denominator Return New Rational(Top, Bottom) End Operator Public Shared Operator *(ByVal First As Rational, ByVal Second As Rational) As Rational Dim Top As Long Dim Bottom As Long Top = First.Numerator * Second.Numerator Bottom = First.Denominator * Second.Denominator Return New Rational(Top, Bottom) End Operator Public Shared Operator /(ByVal First As Rational, ByVal Second As Rational) As Rational Dim Top As Long Dim Bottom As Long Top = First.Numerator * Second.Denominator Bottom = First.Denominator * Second.Numerator Return New Rational(Top, Bottom) End Operator Public Overrides Function ToString() As String Dim Numer As Long Dim Denom As Long Numer = Num / Arithmetic.GreatestCommonDivisor(Num, Den) Denom = Den / Arithmetic.GreatestCommonDivisor(Num, Den) If Denom = 1 Then Return Numer.ToString() Else Return String.Format("{0}/{1}", Numer, Denom) End If End Function End Class 2. Access the Algebra.vb file and change it as follows: Module Algebra Public Function Main() As Integer Dim a, b, c, d As Long Dim FirstFraction As Rational = Nothing Dim SecondFraction As Rational = Nothing
MsgBox("This program allows you to perform " & "an arithmetic operation on two fractions") a = CLng(InputBox("=-= First Fraction =-=" & vbCrLf & "Enter the numerator:")) b = CLng(InputBox("=-= First Fraction =-=" & vbCrLf & "Enter the denominator: ")) c = CLng(InputBox("=-= Second Fraction =-=" & vbCrLf & "Enter the numerator:")) d = CLng(InputBox("=-= Second Fraction =-=" & vbCrLf & "Enter the denominator:")) FirstFraction = New Rational(a, b) MsgBox(String.Format("First Fraction: FirstFraction)) SecondFraction = New Rational(c, d) MsgBox(String.Format("Second Fraction: SecondFraction)) Dim Dim Dim Dim Addition As Rational Subtraction As Rational Multiplication As Rational Division As Rational {0}/{1} => {2}", a, b, {0}/{1} => {2}", c, d,
Addition = FirstFraction + SecondFraction MsgBox(String.Format("Addition: {0}/{1} + {2}/{3} = {4}", a, b, c, d, Addition)) Subtraction = FirstFraction - SecondFraction MsgBox(String.Format("Addition: {0}/{1} + {2}/{3} = {4}", a, b, c, d, Subtraction)) Multiplication = FirstFraction * SecondFraction MsgBox(String.Format("Addition: {0}/{1} + {2}/{3} = {4}", a, b, c, d, Multiplication)) Division = FirstFraction / SecondFraction MsgBox(String.Format("Addition: {0}/{1} + {2}/{3} = {4}", a, b, c, d, Division)) Return 0 End Function End Module 3. To execute the application, on the main menu, click Debug -> Start Debugging
4. Click OK 5. When requested, enter the first numerator as 128 and press Enter 6. Enter the first denominator as 54 and press Enter 7. Enter the second numerator as 88 and press Enter 8. Enter the second denominator as 36 and press Enter
Dim N As Integer = (Nbr << Shifts) Dim Nat As Natural = New Natural(N) Return Nat End Operator Public Overrides Function ToString() As String Return Number.ToString() End Function End Class Here is an example of using the operator: Public Module Exercise Public Function Main() As Integer Dim Nbr As Natural Nbr = New Natural(1248) MsgBox("Shiftting the bits of " & Nbr.ToString() & " to the left by 4 is " & (Nbr << 4).ToString()) Return 0 End Function End Module This would produce:
For the operators that join or disjoin two series of bits: The first argument must be the class on which you are working. The second argument can be an integer. Here is an example: Public Shared Operator And(ByVal Value As Natural, ByVal Constant As Integer) As Natural Dim Result As Integer = Value.Number And Constant Return New Natural(Result) End Operator ----------------------------------------------------------------------Public Module Exercise Public Function Main() As Integer Dim Nbr As Natural Nbr = New Natural(286) MsgBox("286 AND 4075 = " & (Nbr And 4075).ToString()) Return 0 End Function End Module
The first argument must be the class on which you are working. The second argument can be a class of the same type as the first argument. Here is an example: Public Class Natural Public Number As Integer Public Sub New(ByVal N As Integer) Number = N End Sub Public Shared Operator Not(ByVal Value As Natural) As Natural Dim Nbr As Integer = Value.Number
Dim N As Integer = Not Nbr Dim Nat As Natural = New Natural(N) Return Nat End Operator Public Shared Operator +(ByVal Value As Natural, ByVal Add As Integer) As Natural Dim Nbr As Integer = Value.Number Dim N As Integer = Nbr + Add Dim Nat As Natural = New Natural(N) Return Nat End Operator Public Shared Operator <<(ByVal Value As Natural, ByVal Shifts As Integer) As Natural Dim Nbr As Integer = Value.Number Dim N As Integer = (Nbr << Shifts) Dim Nat As Natural = New Natural(N) Return Nat End Operator Public Shared Operator And(ByVal Value As Natural, ByVal Constant As Integer) As Natural Dim Result As Integer = Value.Number And Constant Return New Natural(Result) End Operator Public Shared Operator And(ByVal Operand1 As Natural, ByVal Operand2 As Natural) As Natural Dim Result As Integer = Operand1.Number And Operand2.Number Return New Natural(Result) End Operator Public Overrides Function ToString() As String Return Number.ToString() End Function End Class --------------------------------------------------Public Module Exercise Public Function Main() As Integer Dim Nbr1 As Natural = New Natural(52) Dim Nbr2 As Natural = New Natural(2447) MsgBox("52 AND 2447 = " & (Nbr1 And Nbr2).ToString()) Return 0 End Function End Module
This would produce:
Comparison Operators
As its name implies, a comparison is used to find out whether one of two values is higher than the other. The values must be of the same type. Comparison operators go in pair. That is, if you want to compare two values for equality, you must also be able to know when they are different. For this reason, if you decide to overload a comparison operator, you must also overload its opposite: If you overload =, you must also overload <> and vice versa If you overload <, you must also overload > and vice versa If you overload <=, you must also overload >= and vice versa If you overload IsTrue, you must also overload IsFalse and vice versa We know that the Object class is equipped with a method named Equals. That method makes it possible to find out whether one object is equal to another. And since all classes in a Visual Basic application derive from Object, if you decide to overload a couple of comparison operators, you should also override the Equals() method.
Restricted Operators
Some operators either cannot be overloaded or depend on other operators being overloaded. The following operators cannot be overloaded: =, AddressOf, AndAlso, AsType, GetType, Is, IsNot, New, OrElse, and TypeOf ... Is.
Home
Inheritance
Introduction to Inheritance
Definition
Imagine you create a class used to process calculations for a circle. The class may appear as follows: Module Exercise Public Class Circle Public Radius As Double Public Function CalculateDiameter() As Double Return Radius * 2 End Function Public Function CalculateCircmuference() As Double Return CalculateDiameter() * 3.14159 End Function Public Function CalculateArea() As Double Return Radius * Radius * 3.14159 End Function End Class Public Function Main() As Integer Dim circ As Circle = New Circle circ.Radius = 25.84 Console.WriteLine(" -=- Circle Characteristics -=-") Console.WriteLine("Radius: {0} ", circ.Radius) Console.WriteLine("Diameter: {0} ", circ.CalculateDiameter()) Console.WriteLine("Circmuference: {0} ", circ.CalculateCircmuference()) Console.WriteLine("Area: {0} " & vbCrLf, circ.CalculateArea()) Return 0 End Function End Module This would produce: -=- Circle Characteristics -=Radius: 25.55 Diameter: 51.1 Circmuference: 160.535249 Area: 2050.837805975 After creating this class, imagine you want to create another class used to process a sphere. You may start thinking of creating a new class and redefining the members similar to those that belong to the above Circle class. To make this easier, you may just select the code of the Circle class, copy it, and then paste it in your document. Fortunately, when a class hold a foundation that another class can use, you can create the new class that is based on the old one: this is the foundation of class inheritance, or simply called inheritance. Inheritance is the process of creating a new class that is based on an existing class.
Class Derivation
As you may have guessed, in order to implement inheritance, you must first have a class that provides the fundamental definition or behavior you need. There is nothing magical about such a class. It could appear exactly like any of the classes we have used so far. The above Circle class is used to process a circle. It can request or provide a radius. It can also calculate the circumference and the area of a circle. Since a sphere is primarily a 3-dimensional circle, and if you have a class for a circle already, you can simply create your sphere class that uses the already implemented behavior of a circle class. Creating a class that is based on another class is also referred to as deriving a class from another. The first class serves as parent or base. The class that is based on another class is also referred to as child or derived. To create a class based on another, you use the following formula: Class Child Inherits Parent ' Body of the new class End Class In this formula, you start with the Class keyword, followed by a name for your new class, followed
by an end of line. On the next line, type the Inherits keyword, followed by the name of the class on which the new Child class would be based. Of course, the Parent class must have been defined; that is, the compiler must be able to find its definition. Based on the above formula, you can create a sphere class based on the earlier mentioned Circle class as follows: Public Class Circle End Class Class Sphere Inherits Circle End Class If you want to be able to access the class from other languages, you can precede its name with the Public keyword: Public Class Circle End Class Public Class Sphere Inherits Circle End Class Otherwise, if you intend to use it only in the current project, you can precede the Class of the class' name with the Private keyword.
Characteristics of Inheritance
Private Members
After deriving a class, it becomes available and you can use it just as you would any other class. Here is an example: Module Exercise Public Function Main() As Integer Dim ball As Sphere = New Sphere Return 0 End Function End Module When a class is based on another class, all public members of the parent class are made available to the derived class that can use them as necessary. While other methods and classes can also use the public members of a class, the difference is that the derived class can call the public members of the parent as if they belonged to the derived class. That is, the child class doesn't have to "qualify" the public members of the parent class when these public members are used in the body of the derived class. This is illustrated in the following program:
Code File: Circle.vb
Public Class Circle Public Radius As Double Public Function CalculateDiameter() As Double Return Radius * 2 End Function Public Function CalculateCircumference() As Double Return CalculateDiameter() * 3.14159 End Function End Class Public Class Sphere Inherits Circle Public Sub ShowCharacteristics() ' Because Sphere is based on Circle, you can access ' any public member(s) of Circle without qualifying it(them) Radius = 35.84 Console.WriteLine("Circle Characteristics") Console.WriteLine("=======================================================") Console.WriteLine("Radius: {0}", Radius) Console.WriteLine("Diameter: {0}", CalculateDiameter()) Console.WriteLine("Circumference: {0}", CalculateCircumference()) Console.WriteLine("=======================================================") End Sub End Class
Code File: Exercise.vb
Module Exercise
Public Function Main() As Integer Dim ball As Sphere = New Sphere ball.ShowCharacteristics() Return 0 End Function End Module This would produce: Sphere Characteristics Radius: 35.84 Diameter: 71.68 Circumference: 225.1891712 Based on the relationship between a child class and its parent, you can use Me in the child to access the public members of the parent class. Here is an example: Public Class Circle Public Radius As Double Public Function CalculateDiameter() As Double Return Radius * 2 End Function Public Function CalculateCircumference() As Double Return CalculateDiameter() * 3.14159 End Function End Class Public Class Sphere Inherits Circle Public Sub ShowCharacteristics() ' Because Sphere is based on Circle, you can access ' any public member(s) of Circle without qualifying it(them) Me.Radius = 35.84 Console.WriteLine("Circle Characteristics") Console.WriteLine("=======================================================") Console.WriteLine("Radius: {0}", Me.Radius) Console.WriteLine("Diameter: {0}", Me.CalculateDiameter()) Console.WriteLine("Circumference: {0}", Me.CalculateCircumference()) Console.WriteLine("=======================================================") End Sub End Class We mentioned that, when deriving a new class based on an existing one, all public members of the parent class are accessible to its child classes. In fact, those public members are also available to all other non-child classes and external procedures of the parent class. On the other hand, when creating a class, if you think that a certain member would not need to be accessed outside of the class, you should make it private by starting it with the Private keyword. Here is an example: Public Class Circle Public Radius As Double Private Function ShowDescription() Return "A circle is a round geometric shape constructed " & _ "so that all considered points of the shape are " & _ "at an equal distance from a common point called " & _ "the center. Also, two equally opposite points from " & _ "the center are at the exact same dictance from that center." End Function Public Function CalculateDiameter() As Double Return Radius * 2 End Function Public Function CalculateCircumference() As Double Return CalculateDiameter() * 3.14159 End Function End Class After creating a class, its private members are not accessible to clients of the class, not even to the children of that class. If you attempt to access a private member of a class outside of that class, you would receive an error. That what would happen with the following program: Public Class Circle Public Radius As Double Private Function ShowDescription() Return "A circle is a round geometric shape constructed " & _ "so that all considered points of the shape are " & _ "at an equal distance from a common point called " & _ "the center. Also, two equally opposite points from " & _ "the center are at the exact same dictance from that center." End Function Public Function CalculateDiameter() As Double Return Radius * 2 End Function Public Function CalculateCircumference() As Double Return CalculateDiameter() * 3.14159 End Function
End Class Public Class Sphere Inherits Circle Public Sub ShowCharacteristics() ' Because Sphere is based on Circle, you can access ' any public member(s) of Circle without qualifying it(them) Me.Radius = 35.84 Console.WriteLine("Circle Characteristics") Console.WriteLine("=======================================================") Console.WriteLine("Description: {0}", ShowDescription()) Console.WriteLine("Radius: {0}", Me.Radius) Console.WriteLine("Diameter: {0}", Me.CalculateDiameter()) Console.WriteLine("Circumference: {0}", Me.CalculateCircumference()) Console.WriteLine("=======================================================") End Sub End Class
Protected Members
When creating a class that would be used as the base of other classes, in some cases, you may want to create a special relationship among a class and its eventual children. For example, you may want to create some members of the parent class that only its derived class can access. These types of members must be created with the Protected keyword. Here is an example: Public Class Circle Protected Radius As Double Private Function ShowDescription() Return "A circle is a round geometric shape constructed " & _ "so that all considered points of the shape are " & _ "at an equal distance from a common point called " & _ "the center. Also, two equally opposite points from " & _ "the center are at the exact same dictance from that center." End Function Public Function CalculateDiameter() As Double Return Radius * 2 End Function Public Function CalculateCircumference() As Double Return CalculateDiameter() * 3.14159 End Function End Class Not just the member variables but you can also create methods as protected as long as you intend it only for the class and its children. Remember that a protected member cannot be accessed by the clients of the class, only by the class itself and its children. When accessing the protected members of a class from its children, you can use Me to locate those members: Me gives you access to non-Shared public and protected members of both the parent(s) and its class. Here is an example: Public Class Circle Protected Radius As Double Protected Function ShowDescription() Return "A circle is a round geometric shape constructed " & _ "so that all considered points of the shape are " & _ "at an equal distance from a common point called " & _ "the center. Also, two equally opposite points from " & _ "the center are at the exact same dictance from that center." End Function Public Function CalculateDiameter() As Double Return Radius * 2 End Function Public Function CalculateCircumference() As Double Return CalculateDiameter() * 3.14159 End Function End Class Public Class Sphere Inherits Circle Public Sub ShowCharacteristics() ' Because Sphere is based on Circle, you can access ' any public member(s) of Circle without qualifying it(them) Me.Radius = 35.84 Console.WriteLine("Circle Characteristics") Console.WriteLine("=======================================================") Console.WriteLine("Description: {0}", Me.ShowDescription()) Console.WriteLine("-=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=-") Console.WriteLine("Radius: {0}", Me.Radius) Console.WriteLine("Diameter: {0}", Me.CalculateDiameter()) Console.WriteLine("Circumference: {0}", Me.CalculateCircumference()) Console.WriteLine("=======================================================") End Sub End Class
Previous
Next
Polymorphism
Polymorphism Fundamentals
Introduction
As mentioned already, inheritance allows you to reuse, in a child class, code that is already implemented in a parent class. In some cases, that original code will be enough. In some other cases, you will need to apply new behavior to a child class even though the parent class already has a behavior close to what you seek. Re-creating a method in a child class using the same signature method of a parent class is referred to as overriding. Based classes have the same member but implemented differently, you need to know what particular member you are referring to, the basis of polymorphism. (name and arguments, if any) of a on this, if a derived and a parent when accessing that in your code, the parent or the derived's. This is
Overriding a Method
When creating the above two classes, imagine that you want to create a method that displays the characteristics of each shape. The method would belong to its corresponding class. This can be done as follows:
File: Circle.vb
Public Class Circle Protected Radius As Double Protected Function ShowDescription() Return "A circle is a round geometric shape " & vbCrLf & _ "constructed so that all considered points of the " & vbCrLf & _ "shape are at an equal distance from a common point " & vbCrLf & _ "called the center. Also, two equally opposite points " & vbCrLf & _ "from the center are at the exact same dictance from " & vbCrLf & _ "that center." End Function Public Function CalculateDiameter() As Double Return Radius * 2 End Function Public Function CalculateCircumference() As Double Return CalculateDiameter() * 3.14159 End Function Public Sub ShowCharacteristics() Console.WriteLine("Circle Characteristics") Console.WriteLine("=======================================================") Console.WriteLine("Description: {0}", Me.ShowDescription()) Console.WriteLine("-=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=-") Console.WriteLine("Radius: {0}", Radius) Console.WriteLine("Diameter: {0}", CalculateDiameter()) Console.WriteLine("Circumference: {0}" & vbCrLf, CalculateCircumference()) End Sub End Class Public Class Sphere Inherits Circle Public Sub ShowCharacteristics() ' Because Sphere is based on Circle, you can access ' any public member(s) of Circle without qualifying it(them) Console.WriteLine("Sphere Characteristics") Console.WriteLine("=======================================================") Console.WriteLine("Description: {0}", Me.ShowDescription()) Console.WriteLine("-=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=-") Console.WriteLine("Radius: {0}", Me.Radius) Console.WriteLine("Diameter: {0}", Me.CalculateDiameter()) Console.WriteLine("Circumference: {0}", Me.CalculateCircumference()) Console.WriteLine("=======================================================") End Sub End Class When creating a class such as the above Circle, if you create a member that the class' children would override, you can (should/must) indicate this to the compiler. This is done by preceding it with the Overridable keyword. This would be done as follows: Public Class Circle Public Ovirridable Sub ShowCharacteristics()
End Sub End Class Private Class Sphere Inherits Circle Public Sub ShowCharacteristics() End Sub End Class Once the member has been marked as overridable, when implementing the child class, in order to override it, you must mark the corresponding member of the child class as override. To do this, precede it with the Overrides keyword. This would be done as follows:
File: Circle.vb
Public Class Circle Protected Radius As Double Protected Overridable Function ShowDescription() Return "A circle is a round geometric shape " & vbCrLf & _ "constructed so that all considered points of the " & vbCrLf & _ "shape are at an equal distance from a common point " & vbCrLf & _ "called the center. Also, two equally opposite points " & vbCrLf & _ "from the center are at the exact same dictance from " & vbCrLf & _ "that center." End Function Public Function CalculateDiameter() As Double Return Radius * 2 End Function Public Function CalculateCircumference() As Double Return CalculateDiameter() * 3.14159 End Function Public Overridable Sub ShowCharacteristics() Me.Radius = 35.84 Console.WriteLine("Circle Characteristics") Console.WriteLine("=======================================================") Console.WriteLine("Description: {0}", Me.ShowDescription()) Console.WriteLine("-=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=-") Console.WriteLine("Radius: {0}", Me.Radius) Console.WriteLine("Diameter: {0}", Me.CalculateDiameter()) Console.WriteLine("Circumference: {0}" & vbCrLf, Me.CalculateCircumference()) End Sub End Class Public Class Sphere Inherits Circle Protected Overrides Function ShowDescription() Return "A sphere is a three-dimensional geometric " & vbCrLf & _ "shape based on a circle. It is constructed " & vbCrLf & _ "so that all considered points around the shape " & vbCrLf & _ "are at an equal distance from a common point " & vbCrLf & _ "called the center. Like the circle, two equally " & vbCrLf & _ "opposite points from the center are at the exact " & vbCrLf & _ "same dictance from that center." End Function Public Overrides Sub ShowCharacteristics() ' Because Sphere is based on Circle, you can access ' any public member(s) of Circle without qualifying it(them) Me.Radius = 35.84 Console.WriteLine("Sphere Characteristics") Console.WriteLine("=======================================================") Console.WriteLine("Description: {0}", Me.ShowDescription()) Console.WriteLine("-=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=-") Console.WriteLine("Radius: {0}", Me.Radius) Console.WriteLine("Diameter: {0}", Me.CalculateDiameter()) Console.WriteLine("Circumference: {0}", Me.CalculateCircumference()) Console.WriteLine("=======================================================") End Sub End Class
File: Exercise.vb
Module Exercise Public Function Main() As Integer Dim circ As Circle = New Circle circ.ShowCharacteristics() Dim ball As Sphere = New Sphere ball.ShowCharacteristics() Return 0 End Function End Module
This would produce: Circle Characteristics ======================================================= Description: A circle is a round geometric shape constructed so that all considered points of the shape are at an equal distance from a common point called the center. Also, two equally opposite points from the center are at the exact same dictance from that center. -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=Radius: 35.84 Diameter: 71.68 Circumference: 225.1891712 Sphere Characteristics ======================================================= Description: A sphere is a three-dimensional geometric shape based on a circle. It is constructed so that all considered points around the shape are at an equal distance from a common point called the center. Like the circle, two equally opposite points from the center are at the exact same dictance from that center. -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=Radius: 35.84 Diameter: 71.68 Circumference: 225.1891712 ======================================================= If you mark as member of a child class with Overrides, it must have a corresponding member in the parent class and that corresponding member must be marked with the Overridable keyword.
Shadowing a Method
You can notice in the above example that the derived class produces the same results as the base class. In reality, inheritance is used to solve various Object-Oriented Programming (OOP) problems. One of them consists of customizing, adapting, or improving the behavior of a feature of the parent class. For example, although both the circle and the sphere have an area, their areas are not the same. A circle is a flat surface but a sphere is a volume, which makes its area very much higher. Since they use different formulas for their respective area, you should implement a new version of the area in the sphere. This would be done as follows: Public Class Circle Public Radius As Double Public Function CalculateArea() As Double Return Radius * Radius * 3.14159 End Function End Class Private Class Sphere Inherits Circle Public Function CalculateArea() As Double Return 4 * Radius * Radius * 3.14159 End Function End Class Imagine that, in a method of the Sphere class, you call an Area() method, even if you use Me, it may not appear clear what Area() you are accessing. If you create a member, such as a method, in the child class and that has the same signature as an existing member of a parent class, to make sure that you access the derived version of the member, you can hide the corresponding member of the parent class. To do this, precede the member of the child class with the Shadows keyword. This would be done as follows:
File: Circle.vb
Public Class Circle Protected Radius As Double Protected Overridable Function ShowDescription() Return "A circle is a round geometric shape " & vbCrLf & _ "constructed so that all considered points of the " & vbCrLf & _ "shape are at an equal distance from a common point " & vbCrLf & _ "called the center. Also, two equally opposite points " & vbCrLf & _ "from the center are at the exact same dictance from " & vbCrLf & _ "that center." End Function Public Function CalculateDiameter() As Double Return Radius * 2 End Function Public Function CalculateCircumference() As Double Return CalculateDiameter() * 3.14159 End Function Public Function CalculateArea() As Double Return Radius * Radius * 3.14159 End Function
Public Overridable Sub ShowCharacteristics() Me.Radius = 35.84 Console.WriteLine("Circle Characteristics") Console.WriteLine("=======================================================") Console.WriteLine("Description: {0}", Me.ShowDescription()) Console.WriteLine("-=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=-") Console.WriteLine("Radius: {0}", Radius) Console.WriteLine("Diameter: {0}", Me.CalculateDiameter()) Console.WriteLine("Circumference: {0}", Me.CalculateCircumference()) Console.WriteLine("Area: {0}", Me.CalculateArea()) Console.WriteLine("=======================================================") End Sub End Class Public Class Sphere Inherits Circle Protected Overrides Function ShowDescription() Return "A sphere is a three-dimensional geometric " & vbCrLf & _ "shape based on a circle. It is constructed " & vbCrLf & _ "so that all considered points around the shape " & vbCrLf & _ "are at an equal distance from a common point " & vbCrLf & _ "called the center. Like the circle, two equally " & vbCrLf & _ "opposite points from the center are at the exact " & vbCrLf & _ "same dictance from that center." End Function Public Shadows Function CalculateArea() As Double Return 4 * Radius * Radius * 3.14159 End Function Public Function CalculateVolume() As Double Return 4 * 3.14159 * Radius * Radius * Radius / 3 End Function Public Overrides Sub ShowCharacteristics() ' Because Sphere is based on Circle, you can access ' any public member(s) of Circle without qualifying it(them) Me.Radius = 35.84 Console.WriteLine("Sphere Characteristics") Console.WriteLine("=======================================================") Console.WriteLine("Description: {0}", Me.ShowDescription()) Console.WriteLine("-=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=-") Console.WriteLine("Radius: {0}", Me.Radius) Console.WriteLine("Diameter: {0}", Me.CalculateDiameter()) Console.WriteLine("Circumference: {0}", Me.CalculateCircumference()) Console.WriteLine("Area: {0}", Me.CalculateArea()) Console.WriteLine("Volume: {0}", Me.CalculateVolume()) Console.WriteLine("=======================================================") End Sub End Class
File: Exercise.vb
Module Exercise Public Function Main() As Integer Dim circ As Circle = New Circle circ.ShowCharacteristics() Dim ball As Sphere = New Sphere ball.ShowCharacteristics() Return 0 End Function End Module This would produce: Circle Characteristics ======================================================= Description: A circle is a round geometric shape constructed so that all considered points of the shape are at an equal distance from a common point called the center. Also, two equally opposite points from the center are at the exact same dictance from that center. -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=Radius: 35.84 Diameter: 71.68 Circumference: 225.1891712 Area: 4035.389947904 ======================================================= Sphere Characteristics ======================================================= Description: A sphere is a three-dimensional geometric shape based on a circle. It is constructed so that all considered points around the shape are at an equal distance from a common point called the center. Like the circle, two equally opposite points from the center are at the exact same dictance from that center. -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=Radius: 35.84 Diameter: 71.68
String Conversion
One of the functionalities provided by the Object class consists of converting a class to a string.
Because this can mean different things to different classes. The Object class provides the method named ToString. Its syntax is: Public Overridable Function ToString() As String In some cases, you can directly call this method as it is available to your class already. Here is an example: Module Exercise Public Class Square Inherits Object Public Side As Double Function CalculatePerimeter() As Double Return Side * 4 End Function Function CalculateArea() As Double Return Side * Side End Function End Class Public Function Main() As Integer Dim sqr As Square = New Square sqr.ToString() Return 0 End Function End Module Otherwise, most of the time, you will need to indicate to the compiler how this method should be interpreted by your class, which is done by overriding it. To override this method, follow the rules of overriding a method by associating the Overrides keyword with the syntax of the method. In the body of the method, implement it as you see fit. Here is an example: Module Exercise Public Class Square Inherits Object Public Side As Double Function CalculatePerimeter() As Double Return Side * 4 End Function Function CalculateArea() As Double Return Side * Side End Function Public Overrides Function ToString() As String Return "Square Characteristics" & vbCrLf & _ "Side: " & CStr(Side) & vbCrLf & _ "Perimeter: " & CStr(CalculatePerimeter()) & vbCrLf & _ "Area: " & CStr(CalculateArea()) End Function End Class End Module Because the Object.ToString() method returns a String object, you can assign its result to a string or pass it to a function or method that takes a string as argument. Here is an example: Module Exercise Public Class Square Inherits Object Public Side As Double Function CalculatePerimeter() As Double Return Side * 4 End Function Function CalculateArea() As Double Return Side * Side End Function Public Overrides Function ToString() As String Return "Square Characteristics" & vbCrLf & _ "Side: " & CStr(Side) & vbCrLf & _ "Perimeter: " & CStr(CalculatePerimeter()) & vbCrLf & _ "Area: " & CStr(CalculateArea()) End Function End Class Public Function Main() As Integer Dim sqr As Square = New Square Console.WriteLine(sqr.ToString()) Return 0 End Function End Module
Console.Write("Enter Side: ") sqr2.Side = Double.Parse(Console.ReadLine()) Console.WriteLine() Console.WriteLine("{0}", sqr1.ToString()) Console.WriteLine() Console.WriteLine("{0}", sqr2.ToString()) Console.WriteLine() Console.WriteLine("Squares Equality: {0}", sqr1.Equals(sqr2)) Return 0 End Function End Module Here is an example of executing it: =+= First Square =+= Enter Side: 125.84 =+= Second Square =+= Enter Side: 125.84 Square Characteristics Side: 125.84 Perimeter: 503.36 Area: 15835.71 Square Characteristics Side: 125.84 Perimeter: 503.36 Area: 15835.71 Squares Equality: False Notice that, although both square instances have the same Side value and produce the same area, the compiler renders them not equal. This is an indication that the compiler doesn't know how to compare two instances of the Square class. The solution to this type of problem is to override the Equals() method in your class instead of relying on the default implementation from the Object class. Here are two overrides of the Equals() methods as overridden for the above Square class: Module Exercise Public Class Square Inherits Object Public Side As Double Function CalculatePerimeter() As Double Return Side * 4 End Function Function CalculateArea() As Double Return Side * Side End Function Public Overrides Function ToString() As String Return "Square Characteristics" & vbCrLf & _ "Side: " & CStr(Side) & vbCrLf & _ "Perimeter: " & CStr(CalculatePerimeter()) & vbCrLf & _ "Area: " & CStr(CalculateArea()) End Function Public Overridable Overloads Function Equals(ByVal sqr As Square) As Boolean ' We will only compare the side of the square ' because the calculations of the perimeter and the area ' directly depend on the side ' If the side of the square passed as argument is equal ' to the side of this object, both objects are equal If sqr.Side = Me.Side Then Return True ' If the sides are not equal, then the objects are not equal Return False End Function Public Overloads Shared Function Equals(ByVal first As Square, _ ByVal second As Square) As Boolean ' We will only compare the side of the square ' If the side of the first square is equal ' to the side of the second one, then both squares are equal If first.Side = second.Side Then Return True ' If the sides are not equal, then the objects are not equal Return False End Function End Class Public Function Main() As Integer Dim sqr1 As Square = New Square Dim sqr2 As Square = New Square Console.WriteLine(" =+= First Square =+=") Console.Write("Enter Side: ") sqr1.Side = Double.Parse(Console.ReadLine()) Console.WriteLine(" =+= Second Square =+=") Console.Write("Enter Side: ") sqr2.Side = Double.Parse(Console.ReadLine()) Console.WriteLine() Console.WriteLine("{0}", sqr1.ToString()) Console.WriteLine("{0}", sqr2.ToString())
Console.WriteLine("Squares Equality: {0}", sqr1.Equals(sqr2)) Console.WriteLine() Console.WriteLine(" =+= First Square =+=") Console.Write("Enter Side: ") sqr1.Side = Double.Parse(Console.ReadLine()) Console.WriteLine(" =+= Second Square =+=") Console.Write("Enter Side: ") sqr2.Side = Double.Parse(Console.ReadLine()) Console.WriteLine() Console.WriteLine("{0}", sqr1.ToString()) Console.WriteLine() Console.WriteLine("{0}", sqr2.ToString()) Console.WriteLine() Console.WriteLine("Squares Equality: {0}", Equals(sqr1, sqr2)) Return 0 End Function End Module Here is an example of testing the program: =+= First Square =+= Enter Side: 125.84 =+= Second Square =+= Enter Side: 125.84 Square Characteristics Side: 125.84 Perimeter: 503.36 Area: 15835.71 Square Characteristics Side: 125.84 Perimeter: 503.36 Area: 15835.71 Squares Equality: True =+= First Square =+= Enter Side: 38.45 =+= Second Square =+= Enter Side: 16.82 Square Characteristics Side: 38.45 Perimeter: 153.80 Area: 1478.40 Square Characteristics Side: 16.82 Perimeter: 67.28 Area: 282.91 Squares Equality: False Here is another run of the same program: =+= First Square =+= Enter Side: 70.68 =+= Second Square =+= Enter Side: 42.04 Square Characteristics Side: 70.68 Perimeter: 282.72 Area: 4995.66 Square Characteristics Side: 42.04 Perimeter: 168.16 Area: 1767.36 Squares Equality: False =+= First Square =+= Enter Side: 58.26 =+= Second Square =+= Enter Side: 58.26 Square Characteristics Side: 58.26 Perimeter: 233.04 Area: 3394.23 Square Characteristics Side: 58.26 Perimeter: 233.04 Area: 3394.23 Squares Equality: True Notice that, this time, the compiler knows how to perform the comparison of two Square objects using either version of the Equals() method.
Previous
Next
Class Abstraction
An Abstract Class
Introduction
It should appear to us clearly by now that inheritance is useful by allowing us to use an object that was already created but "upgrade" it with new features that were not available when the original object was born. In most cases, when creating a class, you may not thing that other classes would be inherited from it. In fact, this will usually not be your concern: you simply create a class and use it as needed. In some other cases, rather as you build your experience with Visual Basic. You may create a class that, although useful at the time, you may already think of other classes that would be based on it. This means that, at the time you are creating such a class, you would already keep inheritance in mind. Visual Basic provides various features that can assist you with creating and implementing class with different goals in mind.
Abstracting a Class
Imagine that, when creating a class, you already find that it is too or highly generalized to serve one particular purpose. As an example, imagine you start creating a class you intend to use to process calculations for a rectangle, or a square, or a parallelogram, or even a triangle:
Rectangle
Square
Parallelogram
Triangle
You start thinking that the same class could be used for different types of geometric shapes. In this case, instead of creating a different class for each shape, you can create a generalized class that these shapes can be based on. Unfortunately, these shapes, although each characterized as geometric, don't have much in common; otherwise they would not be different. One of their common characteristics is that each has a name. While the parallelogram and the triangle have a base, the rectangle and the square don't explicitly have one. Also, neither the perimeter nor the area of these shapes are calculated the same. Still, as long as you find at least one characteristic that these objects have, you can create a class that would share. In other words, you can create a class that features one or more characteristics that these objects have. Then each object would customize its behavior(s) based on its particular characteristics. This is the basis of abstraction. A class is referred to as abstract when it is only used to lay a foundation for other classes. In the Microsoft Visual Basic language, to create an abstract class, you must precede its Class keyword with MustInherit. Here is an example:
File: Quadrilateral.vb
Public MustInherit Class Quadrilateral End Class After creating a class and marking it as MustInherit, you can add one or more members to it, as done in the previous examples we used so far. Here is an example:
File: Quadrilateral.vb
Public MustInherit Class Quadrilateral Public Function ShowDescription() As String Return "Geometric Shape" End Function End Class If you create a class and mark it as MustInherit, it is considered incomplete. Because of that, although you can declare a variable of that type, you cannot initialize its instance using the New operator. Consider the following example:
File: Exercise.vb
Module Exercise
Public Function Main() As Integer Dim quad As Quadrilateral = New Quadrilateral Console.WriteLine("Description = {0}", quad.Description) Return 0 End Function End Module This would produce an error because you cannot use New to instantiate a MustInherit class. This means that, before using a MustInherit class, you must derive a class from it.
Public MustInherit Class Quadrilateral Public MustOverride Property Area() As Double End Class In the same way, you can add as many members as necessary. You will mark as MustOverride those of your choice and you can create others without MustOverride. Here are examples:
File: Quadrilateral.vb
Public MustInherit Class Quadrilateral Public Function ShowDescription() As String Return "Geometric Shape" End Function Public MustOverride Property Area() As Double End Class After creating a MustInherit class, you can inherit new classes from it using the Inherits keyword we saw in the previous lessons. Here is an example: Public Class Square Inherits Quadrilateral End Class When deriving a class from a MustInherit, the first rule you must observe is that each member of the abstract that was marked as MustOverride must be overridden. Based on this, in our Square class, you must (at least) implement the Area property. Here is an example:
File: Quadrilateral.vb
Public MustInherit Class Quadrilateral Public Function ShowDescription() As String Return "Geometric Shape" End Function Public MustOverride ReadOnly Property Area() As Double End Class Public Class Square Inherits Quadrilateral Public Overrides ReadOnly Property Area() As Double Get Return 0 End Get End Property End Class In the derived class, as a new one, you can add new members as you judge them necessary. Here are examples:
File: Quadrilateral.vb
Public MustInherit Class Quadrilateral Public Function ShowDescription() As String Return "Geometric Shape" End Function
Public MustOverride ReadOnly Property Area() As Double End Class Public Class Square Inherits Quadrilateral Public sd As Double Public Sub New() sd = 0 End Sub Public Sub New(ByVal side As Double) sd = side End Sub Public Property Side() As Double Get Return sd End Get Set(ByVal Value As Double) If Value <= 0 Then sd = 0 Else sd = Value End If End Set End Property Public Overrides ReadOnly Property Area() As Double Get Return sd * sd End Get End Property End Class After deriving a new class from a MustInherit class, you can declare a variable of it and instantiate it using the New operator. Here is an example:
File: Exercise.vb
Module Exercise Public Function Main() As Integer Dim sqr As Square = New Square sqr.Side = 35.75 Console.WriteLine(" -=- Square Characteristics -=-") Console.WriteLine("Description: {0}", sqr.ShowDescription) Console.WriteLine("Side: {0}", sqr.Side) Console.WriteLine("Area: {0}", sqr.Area) Return 0 End Function End Module This would produce: -=- Square Characteristics -=Description: Geometric Shape Side: 35.75 Area: 1278.0625 As mentioned earlier, after creating a MustInherit class, you can declare a variable of it but you cannot instantiate it using the New operator. Consider the following example: Module Exercise Public Function Main() As Integer Dim sqr As Quadrilateral sqr = New Square Return 0 End Function End Module These declaration and instantiation are legal but the (tri) variable gives you access only to members that are present in the parent class. This means that this declaration gives you access to the ShowDescription() method and the Area property of the Quadrilateral class. This is illustrated in the following: Module Exercise Public Function Main() As Integer Dim sqr As Quadrilateral sqr = New Square Console.WriteLine(" -=- Square Characteristics -=-") Console.WriteLine("Description: {0}", sqr.ShowDescription) Console.WriteLine("Area: {0}", sqr.Area) Return 0 End Function
End Module This would produce: -=- Square Characteristics -=Description: Geometric Shape Area: 0 When instantiating a class derived from a MustInherit class, if you want to access its members, you must apply its name to the New operator as we saw in the last example of the previous section. Here is an example: Module Exercise Public Function Main() As Integer Dim sqr As Square = New Square(42.68) Console.WriteLine(" -=- Square Characteristics -=-") Console.WriteLine("Description: {0}", sqr.ShowDescription) Console.WriteLine("Side: {0}", sqr.Side) Console.WriteLine("Area: {0}", sqr.Area) Return 0 End Function End Module This would produce: -=- Square Characteristics -=Description: Geometric Shape Side: 42.68 Area: 1821.5824
Sealed Classes
All of the classes we have used so far can serve as parents of other classes. This is the default behavior of a regular class: the ability to derive a new class from it. In some cases, you may not want any class to be derived from a particular class you are creating. Such a class is referred to as sealed. A class is said to be sealed when you cannot inherit from it. If you try, you would receive an error. To create a sealed class in Microsoft Visual Basic, precede the name of the class with the NotInheritable keyword.
Interfaces
Introduction
We described abstract classes as those intended for inheritance. Another type of class designed for this purpose is referred to as an interface. An interface is a class that creates a foundation that new derived classes can use. As done for an abstract class, you can create original behavior that the deriving classes would use. Unlike abstract classes, you don't implement the members (properties and procedures) of the interface. The general idea of an interface is only to lay a foundation, as creating a structural base, that the new classes would follow, although they can customize the behavior(s) of the parent interface but the parent interface does not "decide" what the behavior of a member would be.
Interface Creation
To create an interface, you start with the Interface keyword followed by the name of the interface. You end the interface definition with an End Interface line. By tradition or good habit, the name of an interface starts with I. Here is an example of a starting interface:
File: RegularTriangle.vb
Public Interface ITriangle End Interface After creating an interface, you can derive a class from it. When deriving from an interface, instead of the Inherits keyword, you use Implements followed by the name of the interface. Here is an example of a new class named Regular and that is based on the above ITriangle interface:
File: RegularTriangle.vb
Public Interface ITriangle End Interface Public Class RegularTriangle Implements ITriangle
End Class As with other classes, once you have derived the class, you can create objects from it and instantiate it using the New operator. Here is an example:
File: Exercise.vb
Module Exercise Public Function Main() As Integer Dim reg As RegularTriangle reg = New RegularTriangle Return 0 End Function End Module As mentioned earlier, the purpose of having an interface is to create a skeleton that derived classes would follow. To do this, in the body of the interface, you can create the necessary members that you want to make available to new classes. The members can be the same types of methods or properties as those we have used in classes so far. Here are examples:
File: RegularTriangle.vb
Public Interface ITriangle ReadOnly Property Name() As String Property Base() As Double Property Height() As Double Function CalculatePerimeter() As Double Function CalculateArea() As Double End Interface The primary rule you must observe when deriving a class from an interface is that you must implement each member of the interface in the derived class. If you omit implementing a member of the parent interface, you would receive an error. When implementing a member of the interface, it must be followed by the Implements keyword, the name of the interface, the period operator, and the name of the member that it is implementing. Based on this, our Regular class can implement the ITriangle interface as follows:
File: RegularTriangle.vb
Public Interface ITriangle ReadOnly Property Name() As String Property Base() As Double Property Height() As Double Function CalculatePerimeter() As Double Function CalculateArea() As Double End Interface Public Class RegularTriangle Implements ITriangle Public Public Public Public bas hgt sd1 sd2 As As As As Double Double Double Double
' Default constructor: the user will specify the dimensions Public Sub New() bas = 0 hgt = 0 sd1 = 0 sd2 = 0 End Sub ' A triangle based on known base and height Public Sub New(ByVal b As Double, ByVal h As Double) bas = b hgt = h End Sub ' A triangle based on the measurements of the sides Public Sub New(ByVal b As Double, ByVal side1 As Double, ByVal side2 As Double) bas = b sd1 = side1 sd2 = side2 End Sub ' A triangle whose all sides and the height are known Public Sub New(ByVal b As Double, ByVal h As Double, _ ByVal side1 As Double, ByVal side2 As Double) bas = b hgt = h sd1 = side1 sd2 = side2 End Sub Public Property Base() As Double Implements ITriangle.Base Get Return bas End Get
Set(ByVal Value As Double) If bas < 0 Then bas = 0 Else bas = Value End If End Set End Property Public Function CalculateArea() As Double Implements ITriangle.CalculateArea Return bas * hgt / 2 End Function Public Function CalculatePerimeter() As Double Implements _ ITriangle.CalculatePerimeter Return bas + sd1 + sd2 End Function Public Property Height() As Double Implements ITriangle.Height Get Return hgt End Get Set(ByVal Value As Double) If hgt < 0 Then hgt = 0 Else hgt = Value End If End Set End Property Public ReadOnly Property Name() As String Implements ITriangle.Name Get Return "Regular Triangle" End Get End Property End Class Once the class has been defined like this, you can then instantiate and use it. Here is an example:
File: Exercise.vb
Module Exercise Public Function Main() As Integer Dim reg As RegularTriangle = New RegularTriangle(35.28, 26.44) Console.WriteLine("Triangle Type: {0}", reg.Name) Console.WriteLine("=-= Characteristics =-=") Console.WriteLine("Base: {0}", reg.Base) Console.WriteLine("Height: {0}", reg.Height) Console.WriteLine("Area: {0}", reg.CalculateArea) Return 0 End Function End Module This would produce: Triangle Type: Regular Triangle =-= Characteristics =-= Base: 35.28 Height: 26.44 Area: 466.4016 In the same way, you can derive other classes from an interface. For example, from our ITriangle class, you can derive an isosceles, a right, or an equilateral triangle. Always remember that when you derive a class, you must implement all of the members of the interface. You can also add new members as you see fit.
An Interface Derived
Like a regular class, an interface can be derived from another interface but an interface cannot derive from a class. To create an interface based on another, use the Inherits keyword as we have used in other classes. Here is an example:
File: RegularTriangle.vb
Public Interface IGeometricShape End Interface Public Interface ITriangle Inherits IGeometricShape End Interface As mentioned for the interfaces, you can use the parent interface to list the members that the deriving classes would implement. Still remember that since an interface cannot implement a member, the member of the parent interface cannot be defined in a derived interface. This implement would wait for the actual class(es) that would be based on the child (or even the parent) interface. Here is an example:
File: RegularTriangle.vb
Public Interface IGeometricShape ReadOnly Property Type() As String End Interface Public Interface ITriangle Inherits IGeometricShape ReadOnly Property Name() As String Property Base() As Double Property Height() As Double Function CalculatePerimeter() As Double Function CalculateArea() As Double End Interface After deriving a class from an interface, when defining the class, you must implement the member of the immediate interface and those of the ancestor interface(s). Here is an example:
File: RegularTriangle.vb
Public Interface IGeometricShape ReadOnly Property Type() As String End Interface Public Interface ITriangle Inherits IGeometricShape ReadOnly Property Name() As String Property Base() As Double Property Height() As Double Function CalculatePerimeter() As Double Function CalculateArea() As Double End Interface Public Class RegularTriangle Implements ITriangle Public Public Public Public bas hgt sd1 sd2 As As As As Double Double Double Double
Public ReadOnly Property Type() As String Implements ITriangle.type Get Return "Triangle" End Get End Property ' Default constructor: the user will specify the dimensions Public Sub New() bas = 0 hgt = 0 sd1 = 0 sd2 = 0 End Sub ' A triangle based on known base and height Public Sub New(ByVal b As Double, ByVal h As Double) bas = b hgt = h End Sub ' A triangle based on the measurements of the sides Public Sub New(ByVal b As Double, ByVal side1 As Double, ByVal side2 As Double) bas = b sd1 = side1 sd2 = side2 End Sub ' A triangle whose all sides and the height are known Public Sub New(ByVal b As Double, ByVal h As Double, _ ByVal side1 As Double, ByVal side2 As Double) bas = b hgt = h sd1 = side1 sd2 = side2 End Sub Public Property Base() As Double Implements ITriangle.Base Get Return bas End Get Set(ByVal Value As Double) If bas < 0 Then bas = 0 Else bas = Value End If End Set End Property Public Function CalculateArea() As Double Implements ITriangle.CalculateArea Return bas * hgt / 2 End Function
Public Function CalculatePerimeter() As Double Implements _ ITriangle.CalculatePerimeter Return bas + sd1 + sd2 End Function Public Property Height() As Double Implements ITriangle.Height Get Return hgt End Get Set(ByVal Value As Double) If hgt < 0 Then hgt = 0 Else hgt = Value End If End Set End Property Public ReadOnly Property Name() As String Implements ITriangle.Name Get Return "Regular" End Get End Property End Class Here is an example of testing the class:
File: Exercise.vb
Module Exercise Public Function Main() As Integer Dim reg As RegularTriangle = New RegularTriangle(35.28, 26.44) Console.WriteLine("Shape Type: {0}", reg.Type) Console.WriteLine("Triangle Type: {0}", reg.Name) Console.WriteLine("=-= Characteristics =-=") Console.WriteLine("Base: {0}", reg.Base) Console.WriteLine("Height: {0}", reg.Height) Console.WriteLine("Area: {0}", reg.CalculateArea) Return 0 End Function End Module This would produce: Shape Type: Triangle Triangle Type: Regular =-= Characteristics =-= Base: 35.28 Height: 26.44 Area: 466.4016
Multiple Inheritance
Multiple inheritance consists of creating a class that is based on more than one parent. In the Microsoft Visual Basic language (in fact in the .NET Framework), you cannot derive a class from more than one class. This functionality is available only with interfaces. To create a class based on more than one interface, after the Implements keyword, enter the name of each interface and separate them with commas. Here is an example: Public Interface IGeometricShape ReadOnly Property Type() As String End Interface Public Interface ICalculation End Interface Public Interface ITriangle Inherits IGeometricShape, ICalculation End Interface The same rules apply for multiple inheritance: you must implements all members of each parent interface. Besides deriving from an interface, you can also create a class that is based on a class and one or more interfaces. To do this, under the line that specifies the name of the class, use the Inherits keyword to specify the name of the parent, press Enter, and use the Implements keyword to specify the name of the class that serves as the parent interface. Here is an example: Public Interface IGeometricShape ReadOnly Property Type() As String End Interface Public Interface ICalculation End Interface
Public Class Geometry End Class Public Interface ITriangle Inherits IGeometricShape, ICalculation End Interface Public Class RegularTriangle Inherits Geometry Implements ITriangle End Class In the same way, you can create a class that is based on more than one interface but it can be based on only one class.
Module Exercise Private Sub ShowCharacteristics() Dim reg As RegularTriangle = New RegularTriangle(35.28, 26.44) Console.WriteLine("Shape Type: {0}", reg.Type) Console.WriteLine("Triangle Type: {0}", reg.Name) Console.WriteLine("=-= Characteristics =-=") Console.WriteLine("Base: {0}", reg.Base) Console.WriteLine("Height: {0}", reg.Height) Console.WriteLine("Area: {0}", reg.CalculateArea) End Sub Public Function Main() As Integer ShowCharacteristics() Return 0 End Function End Module In the same way, you can declare as many class variables as you see fit in a procedure.
Returning an Object
So far, as we have learned since Lesson, we know that a function can be used to return a value. In the same way, you can create a function that returns an object of a class. When creating such a function, set its type as that of the class it would return. The formula to follow is still: Function FunctionName() As ClassName End Function In the body of the class, which is the section between the Function and the End Function lines,
you can perform any assignment you judge necessary. For example you can declare local variables. Before exiting the function, you must make sure it returns a value based on its As type. You can do this using the Return keyword followed by the value to return. Here is an example: Private Function CreateTriangle() As RegularTriangle Dim regTri As RegularTriangle Dim base As Double, height As Double Console.WriteLine("Enter the measurements of the triangle") Console.Write("Base: ") base = CDbl(Console.ReadLine()) Console.Write("Height: ") height = CDbl(Console.ReadLine()) regTri = New RegularTriangle(base, height) Return regTri End Function After defining the function, since it returns a value, when calling it, you can assign it to a variable of the type that it returns. Here is an example: Module Exercise Private Function CreateTriangle() As RegularTriangle Dim regTri As RegularTriangle Dim base As Double, height As Double Console.WriteLine("Enter the measurements of the triangle") Console.Write("Base: ") base = CDbl(Console.ReadLine()) Console.Write("Height: ") height = CDbl(Console.ReadLine()) regTri = New RegularTriangle(base, height) Return regTri End Function Private Sub ShowCharacteristics() Dim reg As RegularTriangle = New RegularTriangle reg = CreateTriangle() Console.WriteLine("Shape Type: {0}", reg.Type) Console.WriteLine("Triangle Type: {0}", reg.Name) Console.WriteLine("=-= Characteristics =-=") Console.WriteLine("Base: {0}", reg.Base) Console.WriteLine("Height: {0}", reg.Height) Console.WriteLine("Area: {0}", reg.CalculateArea) End Sub Public Function Main() As Integer ShowCharacteristics Return 0 End Function End Module Here is a test of the above code: Enter the measurements of the triangle Base: 18.44 Height: 12.62 Shape Type: Triangle Triangle Type: Regular =-= Characteristics =-= Base: 18.44 Height: 12.62 Area: 116.3564
Console.WriteLine("=-= Characteristics =-=") Console.WriteLine("Base: {0}", reg.Base) Console.WriteLine("Height: {0}", reg.Height) Console.WriteLine("Area: {0}", reg.CalculateArea) End Sub Public Function Main() As Integer Dim Angle3 = CreateTriangle() Console.WriteLine() ShowCharacteristics(Angle3) Console.WriteLine() Return 0 End Function End Module Besides the function, in Lesson 5, we saw that, by passing an argument by reference, a sub procedure could return a value. This characteristic also applies to a class passed as argument. When passing the argument, precede it with the ByRef keyword. In the procedure, process the argument as you see fit, unless you choose not to. When calling the procedure, pass it a valid variable based on the type of the argument. Here is an example: Module Exercise Private Sub CreateTriangle(ByRef regTri As RegularTriangle) Dim base As Double, height As Double Console.WriteLine("Enter the measurements of the triangle") Console.Write("Base: ") base = CDbl(Console.ReadLine()) Console.Write("Height: ") height = CDbl(Console.ReadLine()) regTri = New RegularTriangle(base, height) End Sub Private Sub ShowCharacteristics(ByVal reg As RegularTriangle) Console.WriteLine("Shape Type: {0}", reg.Type) Console.WriteLine("Triangle Type: {0}", reg.Name) Console.WriteLine("=-= Characteristics =-=") Console.WriteLine("Base: {0}", reg.Base) Console.WriteLine("Height: {0}", reg.Height) Console.WriteLine("Area: {0}", reg.CalculateArea) End Sub Public Function Main() As Integer Dim Angle3 As RegularTriangle = New RegularTriangle CreateTriangle(Angle3) Console.WriteLine() ShowCharacteristics(Angle3) Console.WriteLine() Return 0 End Function End Module Here is an example of testing it: Enter the measurements of the triangle Base: 50.05 Height: 25.52 Shape Type: Triangle Triangle Type: Regular =-= Characteristics =-= Base: 50.05 Height: 25.52 Area: 638.638
Optional Arguments
When passing an argument of a class, you can specify that it is not required. Such an argument is considered optional. To specify that an argument is optional, when creating its procedure, type the Optional keyword to the left of the argument's name and assign it the default value. All the other rules we reviewed for optional arguments are also applied here.
Procedure Overloading
If you want to create various procedures that takes a class argument, you can create a procedure with the same name but different signatures. This is referred to as overloading the procedure. When doing this, follow the same rules we reviewed for overloading a procedure: the must have
the same name, they cannot have the same number of argument when the arguments at each position are of the same types.
Previous
Home
If NumberOfPages1.Equals(NumberOfPages2) = True Then Console.WriteLine("The first and the second books " & _ "have the same number of pages") Else Console.WriteLine("The first and the second books " & _ "have different number of pages") End If If NumberOfPages1.Equals(NumberOfPages3) = True Then Console.WriteLine("The first and the third books " & _ "have the same number of pages") Else Console.WriteLine("The first and the third books " & _ "have different number of pages") End If Return 0 End Function End Module This would produce: The first and the second books have different number of pages The first and the third books have the same number of pages The first version of the Object.Equals method is declared as Overridable, which means you can override it if you create your own class. The second version of the Object.Equals() method is: Public Shared Function Equals(objA As Object, objB As Object) As Boolean As a Shared method, to use it, you can pass the variables of the two classes whose values you want to compare. In both cases, if the values of the variables are similar, the Equals() method returns true. If they are different, the method returns false. If you are using the Equals() method to compare the variables of two primitive types, the comparison should be straight forward. If you want to use this methods on variables declared from your own class, you should provide your own implementation of this method.
Stringing a Class
In previous lessons, we learned that, to convert the value of a variable declared from a primitive type to a string, you could call the ToString() function. Here is an example: Imports System Module Exercise Public Function Main() As Integer Dim NumberOfPages As Integer = 422 Console.Write("Number of Pages: ") Console.WriteLine(NumberOfPages.ToString()) Return 0 End Function End Module In many programming languages, programmers usually have to overload an (extractor) operator to display the value(s) of class' variable to the screen. The Object class provides an alternative to this somewhat complicated solution, through the ToString() method. It syntax is: Public Overridable Function ToString As String Although the Object class provides this method as non abstract, its implemented version is more useful if you use a primitive type such as Integer, Double and their variances or a string variable. The best way to rely on it consists of overriding it in your own class if you desire to use its role.
Finalizing a Variable
While a constructor, created for each class, is used to instantiate a class. The Object class provides the Finalize() method as a type of destructor.
Home
Number: 424740120 Number: 1009211682 Number: 544356245 Number: 708951978 Number: 759684741 Number: 1325535324 Press any key to continue . . .
Here is one example of running the program: Number: 375271809 Number: 1472524622 Number: 1605850688 Number: 1776011503 Press any key to continue . . . Here is another example of running the same program: Number: 375271809 Number: 1472524622 Number: 1605850688 Number: 1776011503 Press any key to continue . . . Notice that the sequences are the same. In both cases, this indicates that, if you specify a seed, the Random class would generate the same number or the same sequence of numbers.
Public Overridable Function Next(minValue As Integer, _ maxValue As Integer) As Integer The first argument specifies the lowest value that can come from the range. The second argument holds the highest value that the Next() method can generate. Therefore, the method would operate between both values. Here is an example that generates random numbers from 6 to 18: Module Exercise Public Function Main() As Integer Dim nbr As Integer Dim rndNumber As Integer = 0 Dim rndNumbers As Random = New Random For nbr = 1 To 9 rndNumber = rndNumbers.Next(6, 18) Console.Write("Number: ")
Console.WriteLine(rndNumber.ToString()) Next Return 0 End Function End Module Here is an example of running the program: Number: 17 Number: 9 Number: 8 Number: 15 Number: 10 Number: 9 Number: 13 Number: 11 Press any key to continue . . .
Home
While Date is a true data type, DateTime is a class but, even though we have not studied classes yet, we can start using DateTime. We will restrict ourselves to using it only as a data type. We know how to declare a date variable using Date. We also know that, if you already know the components of the date value you want to use, you can include them between two # signs but following the rules of a date format from the Regional Settings of Control Panel. Here is an example: Public Module Exercise Public Function Main() As Integer Dim DateHired As Date DateHired = # 02/08/2003 # MsgBox("Date Hired: " & DateHired) Return 0 End Function End Module This would produce:
A week is a combination of 7 consecutive days of a month. Each day can be recognized by an index from 1 to 7 (1, 2, 3, 4, 5, 6, 7). The day of each index is recognized by a name. In US
English, the first day has an index of 1 is named Sunday while the last day with an index of 7 is named Monday. Like the months of a year, the days of a week have long and short names. These are: US English Day Index 1 2 3 4 5 6 7 Complete Name Sunday Monday Tuesday Wednesday Thursday Friday Saturday Short Name Sun Mon Tue Wed Thu Fri Sat
These are the default in US English. In most calculations, the Visual Basic language allows you to specify what day should be the first in a week. The year is expressed as a numeric value.
Dates Formats
In US English, to express a date value, you can use one of the following formats: mm-dd-yy mm-dd-yyyy You must start the date with a number that represents the month (a number from 1 to 12). After the month value, enter -. Then type the day value as a number between 1 and 28, 29, 30, or 31 depending on the month and the (leap) year. Follow it with -. End the value with a year in 2 or 4 digits. Here are examples 06-12-08 or 10-08-2006. You can also use one of the following formats: dd-mmm-yy dd mmm yy dd-mmmm-yy dd mmmm yy dd-mmm-yyyy dd mmm yyyy dd-mmmm-yyyy dd mmmm yyyy This time, enter the day value followed either by an empty space or -. Follow with the short name of the month in the mmm placeholder or the complete name of the month for the mmmm placeholder, followed by either an empty space or -. End the value with the year, using 2 or 4 digits. As you may know already, in US English, you can start a date with the month. In this case, you can use one of the following formats: mmm dd, yy mmm dd, yyyy mmmm dd, yy mmmm dd, yyyy As seen with the previous formats, mmm represents the short name of a month and mmmm represents the complete name of a month. As mentioned already, the dd day can be expressed with 1 or 2 digits and the single digit can have a leading 0. After the day value, (you must) enter a comma followed by the year either with 2 or 4 digits.
A Date Value
We have seen that, when creating a date, you can include its value between # signs. An alternative is to provide a date as a string. To support this, the Visual Basic language provides a function named DateValue. Its syntax is: Public Function DateValue(ByVal StringDate As String) As DateTime
When calling this function, provide a valid date as argument. The validity depends on the language of the operating system. If working in US English, you can use one of the formats we saw above. Here is an example: Public Function Main() As Integer Dim DateHired As Date DateHired = DateValue("22-Aug-2006") MsgBox("Date Hired: " & DateHired) Return 0 End Function This would produce:
A Date as Serial
An alternative to initializing a date variable is to use a function named DateSerial. Its syntax is: Public Function DateSerial(ByVal [Year] As Integer, _ ByVal [Month] As Integer, _ ByVal [Day] As Integer) As DateTime As you can see, this function allows you to specify the year, the month, and the day of a date value, of course without the # signs. When it has been called, this function returns a Date value. Here is an example: Public Module Exercise Public Function Main() As Integer Dim DateHired As Date DateHired = DateSerial(2003, 02, 08) MsgBox("Date Hired: " & DateHired) Return 0 End Function End Module When passing the values to this function, you must restrict each component to the allowable range of values. You can pass the year with two digits from 0 to 99. Here is an example: Public Module Exercise Public Function Main() As Integer Dim DateHired As Date DateHired = DateSerial(03, 2, 8) MsgBox("Date Hired: " & DateHired) Return 0 End Function End Module If you pass the year as a value between 0 and 99, the compiler would refer to the clock on the computer to get the century. At the time of this writing (in 2008), the century would be 20 and the specified year would be added, which would produce 2003. To be more precise and reduce any confusion, you should always pass the year with 4 digits. The month should (must) be a value between 1 and 12. If you pass a value higher than 12, the compiler would calculate the remainder of that number by 12 (that number MOD 12 = ?). The result of the integer division would be used as the number of years and added to the first argument. The remainder would be used as the month of the date value. For example, if you pass the month as 18, the integer division would produce 1, so 1 year would be added to the first argument. The remainder is 6 (18 MOD 12 = 6); so the month would be used as 6 (June). Here is an example: Public Module Exercise Public Function Main() As Integer Dim DateHired As Date DateHired = DateSerial(2003, 18, 8) MsgBox("Date Hired: " & DateHired) Return 0 End Function
As another example, if you pass the month as 226, the integer division (226 \ 12) produces 18 and that number would be added to the first argument (2003 + 18 = 2021). The remainder of 226 to 12 (226 MOD 12 = 10) is 10 and that would be used as the month. Here is an example: Public Module Exercise Public Function Main() As Integer Dim DateHired As Date DateHired = DateSerial(2003, 226, 8) MsgBox("Date Hired: " & DateHired) Return 0 End Function End Module This would produce:
If the month is passed as 0, it is considered 12 (December) of the previous year. If the month is passed as -1, it is considered 11 (November) of the previous year and so on. If the month is passed as a number lower than -11, the compiler would calculate its integer division to 12, add 1 to that result, use that number as the year, calculate the remainder to 12, and use that result as the month. Depending on the month, the value of the day argument can be passed as a number between 1 and 28, between 1 and 29, between 1 and 30, or between 1 and 31. If the day argument is passed as a number lower than 1 or higher than 31, the compiler uses the first day of the month passed as the second argument. This is 1. If the day is passed as -1, the day is considered the last day of the previous month of the Month argument. For example, if the Month argument is passed as 4 (April) and the Day argument is passed as -1, the compiler would use 31 as the day because the last day of March is 31. If the Month argument is passed as 3 (March) and the Day argument is passed as -1, the compiler would refer to the Year argument to determine whether the year is leap or not. This would allow the compiler to use either 28 or 29 for the day value. The compiler uses this algorithm for any day value passed as the third argument when the number is lower than 1. If the Day argument is passed with a value higher than 28, 29, 30, or 31, the compiler uses this same algorithm in reverse order to determine the month and the day.
date depend on the language and they are defined in the Language and Regional Settings in Control Panel.
As mentioned already, the Month function produces a numeric value that represents the month of a date. Instead of getting the numeric index of the month of a date, if you want to get the name of the month, you can call a function named MonthName. Its syntax is: Public Function MonthName(ByVal Month As Integer, _ Optional ByVal Abbreviate As Boolean = False) As String
This function takes one required and one optional argument. The required argument must represent the value of a month. If it is valid, this function returns the corresponding name. Here is an example: Public Module Exercise Public Function Main() As Integer Dim DateHired As Date = #2/8/2004# MsgBox("Day hired " & MonthName(Month(DateHired))) Return 0 End Function End Module This would produce:
The second argument allows you to specify whether you want to get the complete or the short name. The default is the complete name, in which case the default value of the argument is False. If you want to get the short name, pass the second argument as True. Here is an example: Public Module Exercise Public Function Main() As Integer Dim DateHired As Date = #2/8/2004# MsgBox("Month hired " & MonthName(Month(DateHired), True)) Return 0 End Function End Module
Public Function WeekdayName( _ ByVal Weekday As Integer, _ Optional ByVal Abbreviate As Boolean = False, _ Optional ByVal FirstDayOfWeekValue As FirstDayOfWeek = FirstDayOfWeek.System _ ) As String This function takes one required and two optional arguments. The required argument must be, or represent, a value between 0 and 7. If you pass it as 0, the compiler will refer to the operating system's language to determine the first day of the week, which in US English is Sunday. Otherwise, if you pass one of the above indexes, the function would return the corresponding name of the day. Here is an example: Public Module Exercise Public Function Main() As Integer MsgBox("Day hired: " & WeekdayName(4)) Return 0 End Function End Module This would produce:
If you pass a negative value or a value higher than 7, you would receive an error. The second argument allows you to specify whether you want to get the complete or the short name. The default value of this argument is False, which produces a complete name. If you want a short name, pass the second argument as True. Here is an example: Public Module Exercise Public Function Main() As Integer MsgBox("Day hired: " & WeekdayName(4, True)) Return 0 End Function End Module As mentioned already, the Visual Basic language allows you to specify what days should be the first day of the week. This is the role of the third argument.
To support these primary formats, the Visual Basic language provides a function named FormatDateTime. Its syntax is: Function FormatDateTime( ByVal Expression As DateTime, Optional ByVal NamedFormat As DateFormat = DateFormat.GeneralDate ) As String The first argument of this function must be a valid Date value. The second argument is a member of the DateFormat enumeration. For a date, this argument can be LongDate or ShortDate. Here is an example: Public Function Main() As Integer Dim DateHired$ DateHired$ = FormatDateTime("22-Aug-2006", DateFormat.LongDate) MsgBox("Date Hired: " & DateHired) Return 0 End Function This would produce:
End Module
s n h w ww d y m q yyyy
Second Minute Hour Numeric Weekday Week of the Year Day Numeric Day of the Year Month Quarter Year
The Number argument specifies the number of Interval units you want to add to the DateValue value. If you set it as positive, its value will be added. Here are examples: Public Module Exercise Public Function Main() As Integer Dim LoanStartDate As Date = #6/10/1998# Dim DepositTime As Date = TimeValue("7:14:00") MsgBox("Loan Length: " & DateAdd("yyyy", 5, LoanStartDate)) MsgBox("Time Ready: " & DateAdd("h", 8, DepositTime)) Return 0 End Function End Module This would produce:
We saw that, to add a value to a date or a time, you could call the DateAdd() function. The first argument of this function takes an argument that belongs to an enumeration named DateInterval. Instead of including a character or a combination of characters in double-quotes with the likelihood of a mistake, this enumeration makes it easy by allowing you to select a member of the enumeration and use an easily recognizable name. The members of the DateInterval enumeration are: String Interval s n h w ww d y m q yyyy Enumeration Member DateInterval.Second DateInterval.Minute DateInterval.Hour DateInterval.Weekday DateInterval.Day DateInterval.DayOfYear DateInterval.Month DateInterval.Quarter DateInterval.Year Used To Add Second Minute Hour Numeric Weekday Day Numeric Day of the Year Month Quarter Year
Notice that by using the DateInterval enumeration as argument, the selected interval is easier to select. Here are examples: Public Module Exercise Public Function Main() As Integer Dim LoanStartDate As Date = #6/10/1998# Dim DepositTime As Date = TimeValue("7:14:00")
MsgBox("Loan Length: " & DateAdd(DateInterval.Year, 5, LoanStartDate)) MsgBox("Time Ready: " & DateAdd(DateInterval.Hour, 8, DepositTime)) Return 0 End Function End Module
Public Function Main() As Integer Dim LoanStartDate As Date = #8/12/2003# Dim LoanEndDate As Date = #10/5/2008# Dim Months As Long = DateDiff("m", LoanStartDate, LoanEndDate) MsgBox("Loan Start Date: " & vbTab & LoanStartDate & vbCrLf & _ "Loan End Date: " & vbTab & LoanEndDate & vbCrLf & _ "Loan Length: " & vbTab & Months & " months") Return 0 End Function End Module This would produce:
By default, the days of a week are counted starting on Sunday. If you want to start counting those days on another day, supply the Option1 argument using one of the following values: vbSunday, vbMonday, vbTuesday, vbWednesday, vbThursday, vbFriday, vbSaturday. There are other variances to that argument. If your calculation involves weeks or finding the number of weeks, by default, the weeks are counted starting January 1st. If you want to count your weeks starting at a different date, use the Option2 argument to specify where the program should start. We saw that we could use the DateDiff() function to get the difference between two date or time values. The first argument can be specified as a string. A better idea is to use a member of the DateInterval enumeration. The last two arguments of this function are enumeration types. The fourth argument allows you to specify what day should be considered the first of the week. By default, in US English, the first day is Sunday. To change this, use a member of the FirstDayOfWeek enumeration. The members are: Enumeration Member Constant Value Description The compiler will refer to the operating system to find out what day should be the first. In US English, this should be Sunday Sunday (the default in US English) Monday Tuesday Wednesday Thursday Friday Saturday
FirstDayOfWeek.System
1 2 3 4 5 6 7
By default, the first week of a year is the one that includes January 1st of that year. This is how it is considered in the regular date-based calculations. If you want to change this default setting, you can use the last argument of the DateDiff() function. The value of this argument is from an enumeration named FirstWeekofYear. The members of this enumeration are: Enumeration Member Constant Value Description The compiler will refer to
FirstWeekOfYear.System
the operating system to find out what day should be the first. This should be the week that includes January 1st This will be the week that includes January 1st This will be the first week that includes at least the first 4 days of the year This will be the first week that includes the first 7 4 days of the year
FirstWeekOfYear.Jan1
FirstWeekOfYear.FirstFourDays
FirstWeekOfYear.FirstFullWeek
Home
You can also create the message from other pieces of strings. The Prompt argument can be made of up to 1024 characters. To display the Prompt on multiple lines, you can use either the constant vbCrLf or the combination Chr(10) & Chr(13) between any two strings. Here is an example: Public Function Main() As Integer MsgBox("Your logon credentials have been checked." & _ vbCrLf & "To complete your application, please " & _ "fill out the following survey") Return 0 End Function This would produce:
2 3 4 5
When calling the MsgBox() function and specifying the button, you can use either a member of the MsgBoxStyle enumeration or one of the above constant numeric values. Here is an example that displays the Yes and the No buttons on the message box: Public Function Main() As Integer MsgBox("Your logon credentials have been checked " & _ "and your application has been approved: Congratulations!" & _ vbCrLf & "Before leaving, would you like " & _ "to take our survey survey now?", MsgBoxStyle.YesNo) Return 0 End Function This would produce:
To use one of these icons, you must combine the value of the button to the desired value of the icon. To perform this combination, you use the OR operator. Here is an example: Private Sub cmdMessageBox_Click() Dim iAnswer As Integer iAnswer = MsgBox("Your logon credentials have been checked " & _ "and your application has been approved: Congratulations!" & _ vbCrLf & "Before leaving, would you like " & _ "to take our survey survey now?", vbYesNo Or vbQuestion) End Sub This would produce:
When calling the MsgBox() function, if you want to show one or more buttons and to show an icon, you can use either two members of the MsgBoxStyle enumeration using the OR operator, or you can add one of the constant values of the buttons to another contant values for an icon. For example, 3 + 48 = 51 would result in displaying the buttons Yes, Ne, and Cancel, and the exclamation icon.
effect would be the same as if he had clicked the default button. If you want, you can designate another button as the default. To do this, you can use or add another member of the MsgBoxStyle enumeration. The members used to specify the default button are: Default Button Constant Alternative If the message box contains Numeric more than one button, the Value default would be 0 256 512 The first button The second button The third button
Once again, to specify a default value, use the OR operator to combine a Default Button Constant with any other combination. Here is an example: Public Function Main() As Integer MsgBox("Your logon credentials have been checked " & _ "and your application has been approved: Congratulations!" & _ vbCrLf & "Before leaving, would you like " & _ "to take our survey survey now?", _ MsgBoxStyle.YesNo Or _ MsgBoxStyle.Question Or MsgBoxStyle.DefaultButton2) Return 0 End Function This would produce:
These additional buttons can be used to further control what the user can do: Constant MsgBoxStyle.ApplicationModal MsgBoxStyle.SystemModal Value Effect The user must dismiss the message box before proceeding with the current database The user must dismiss this message before using 4096 any other open application of the computer 0
Notice that the caption is now customized instead of the name of the application. The caption can also be a string created from an expression or emanating from a variable or value.
user clicked on the message box. Depending on the buttons the message box is displaying, after the user has clicked, the MsgBox() function can return a value. The value can be a member of the MsgBoxResult enumeration or a constant numeric value recognized by the Visual Basic language. The value returned can be one of the following values: If the user click The function returns MsgBoxResult.OK MsgBoxResult.Cancel MsgBoxResult.Abort MsgBoxResult.Retry MsgBoxResult.Ignore MsgBoxResult.Yes MsgBoxResult.No or vbOK vbCancel vbAbort vbRetry vbIgnore vbYes vbNo Numeric Value 1 2 3 4 5 6 7
Home
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 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
Delegates
Delegates Fundamentals
Introduction
As done when you declare a variable, when you create and call a procedure, it uses a section of memory of the computer. This section is its address. You can access that area of memory to get to the procedure. Or, you can declare a variable that would be used to access the memory used by the procedure. A function pointer is a special type of variable that is used to access a function using its address. To support function pointers, the .NET Framework provides the concept of delegates. A delegate is not a real function. It provides a syntax for a function that it would be associated with.
Creating a Delegate
Before using a delegate, you must create it or you can use one of the built-in delegates of the .NET Framework. The basic formula to create a delegate is: [modifier] Delegate Sub/Function Name (parameter(s)) As ReturnType The modifier factor can be Public, Private, or Friend. This is followed by either the Delegate Sub or the Delegate Function expression. A delegate must have a name: The Name factor of this formula. The name follows the rules we have been observing for valid names of the Visual Basic language. Because a delegate is some type of a template for a procedure, you must use parentheses. If this procedure will not take any argument, you can leave the parentheses empty. If the delegate will be associated with a sub-procedure, there is no return type. Here is an example: Module Exercise Delegate Sub Messenger() End Module If the delegate is a function-type, you must specify a ReturnType. This can be any of the data types we have used so far, or it can be a class. If you create a procedure that would be associated with a delegate, you can also define it as Shared.
Delegate Sub Messenger() Private Sub ShowMessage() MsgBox("Main message") End Sub Public Function Main() As Integer Dim Mess As Messenger Mess = AddressOf ShowMessage Return 0 End Function End Module After assigning the address of the procedure to the delegate's variable, you can call the delegate as if it were a procedure. Here is an example: Module Exercise Delegate Sub Messenger() Private Sub ShowMessage() MsgBox("Main message") End Sub Public Function Main() As Integer Dim Mess As Messenger Mess = AddressOf ShowMessage Mess() Return 0 End Function End Module In our example, we used a sub-procedure. In the same way, if necessary, you can create a delegate as a function. In this case, you would define a function to associate to that delegate. Then, you can use the same techniques we followed to associate them.
Using delegates, a procedure can be indirectly passed as argument to another procedure. To proceed, first declare the necessary delegate. Here is a example of such a delegate: Module Exercise Delegate Function Squared(ByVal value As Double) As Double End Module A delegate can be passed as argument to a procedure. Such an argument would be used as if it were a procedure itself. This means that, when accessed in the body of the procedure, the name of the delegate must be accompanied by parentheses and if the delegate takes an argument or arguments, the argument(s) must be provided in the parentheses of the called delegate. Here is an example: Module Exercise Private Radius As Double Delegate Function Squared(ByVal value As Double) As Double Public Function Area(ByVal sqd As Squared) As Double Return sqd(Radius) * Math.PI End Function End Module After declaring a delegate, remember to define a procedure that implements the needed behavior of that delegate. Once the procedure is ready, to associate it to a delegate, declare a variable of the type of the delegate using the New operator. In the parentheses of the constructor, access the name of the associated procedure using the AddressOf operator. To access the delegate, call the Invoke() method. Here is an example: Module Exercise Private Radius As Double Delegate Function Squared(ByVal value As Double) As Double Public Function Area(ByVal sqd As Squared) As Double Return sqd(Radius) * Math.PI End Function Public Function ValueTimesValue(ByVal value As Double) As Double Return value * value End Function Public Function Main() As Integer Dim Side As Double = 46.95 Dim AreaDefinition As Squared AreaDefinition = New Squared(AddressOf ValueTimesValue) MsgBox("Circle Calculation" & vbCrLf & _ "Side: " & vbTab & CStr(Side) & vbCrLf & _ "Area: " & vbTab & CStr(AreaDefinition.Invoke(Side))) Return 0 End Function End Module
Home
Namespaces
Introduction
A namespace is a section of code that is recognized with a name. A namespace allows a programmer or a group of programmers who work with others to create code with names that don't conflict with code of the other programmers or other groups. As mentioned already, a namespace is a section of code. Therefore, it must be created in a file before being used.
Creating a Namespace
The formula to create a namespace is: Namespace name End Namespace As you can see, the creation of a namespace starts with the Namespace keyword and ends with the End Namespace expression. On the right side of the starting Namespace keyword, enter a name. The name follows the rules we have used so far for names in the Visual Basic language. Here is an example: Namespace Census End Namespace The section between the starting Namespace line and End Namespace is the body of the namespace. In this body, you can write code as you want. For example, you can create a class in it. Here is an example: Namespace Geometry Public Class Rectangle End Class End Namespace Of course, in the body of the class, you can write the necessary code. Here is an example: Namespace Geometry Public Class Rectangle Public Width As Double Public Height As Double Public Function Perimeter() As Double Return (Width + Height) * 2 End Function Public Function Area() As Double Return Width * Height End Function End Class End Namespace
examples: Namespace Geometry Public Class Rectangle Public Width As Double Public Height As Double Public Function Perimeter() As Double Return (Width + Height) * 2 End Function Public Function Area() As Double Return Width * Height End Function End Class End Namespace Module Exercise Public Function Main() As Integer Dim Rect As Geometry.Rectangle Rect = New Geometry.Rectangle Rect.Width = 40.18 Rect.Height = 28.46 MsgBox("Rectangle Characteristics" & vbCrLf & _ "Width:" & vbTab & vbTab & FormatNumber(Rect.Width) & vbCrLf & _ "Height:" & vbTab & vbTab & FormatNumber(Rect.Height) & vbCrLf & _ "Perimeter:" & vbTab & FormatNumber(Rect.Perimeter()) & vbCrLf & _ "Area:" & vbTab & vbTab & FormatNumber(Rect.Area())) Return 0 End Function End Module In the same way, you can create as many members as you want in the body of a namespace. In the above code, we create our namespace in the same file that contains the Main() function. To better manage your code, you can create your namespaces in different files. Here is an example: Namespace Geometry Public Class Rectangle Public Width As Double Public Height As Double Public Function Perimeter() As Double Return (Width + Height) * 2 End Function Public Function Area() As Double Return Width * Height End Function End Class Public Class Triangle Public Base As Double Public Height As Double Public Function Area() As Double Return Base * Height / 2 End Function End Class End Namespace In the same way, you can create as many namespaces in as many files as you want. A namespace can be created in more than one file.
Importing a Namespace
When accessing each member of a namespace, you can qualify its name wherever you want to use it. Here are examples that use the above namespace that was created in a separate file: Module Exercise Public Function Main() As Integer Dim Rect As Geometry.Rectangle = New Geometry.Rectangle Rect.Width = 40.18 Rect.Height = 28.46 MsgBox("Rectangle Characteristics" & vbCrLf & _ "Width:" & vbTab & vbTab & FormatNumber(Rect.Width) & vbCrLf & _ "Height:" & vbTab & vbTab & FormatNumber(Rect.Height) & vbCrLf & _ "Perimeter:" & vbTab & FormatNumber(Rect.Perimeter()) & vbCrLf & _ "Area:" & vbTab & vbTab & FormatNumber(Rect.Area())) Dim Tri As Geometry.Triangle = New Geometry.Triangle Tri.Base = 36.09 Tri.Height = 28.46 MsgBox("Triangle Characteristics" & vbCrLf & _ "Base:" & vbTab & vbTab & FormatNumber(Tri.Base) & vbCrLf & _
"Height:" & vbTab & vbTab & FormatNumber(Tri.Height) & vbCrLf & _ "Area:" & vbTab & vbTab & FormatNumber(Tri.Area())) Return 0 End Function End Module Instead of qualifying each member, you can import the namespace in the file where you want to use it. To do this, in the top section of the file, type Imports followed by the name of the namespace.
Nesting a Namespace
You can create one namespace inside of another namespace. This is referred to as nesting the namespace. To nest a namespace, create its body in the body of an existing namespace. Here is an example: Namespace Geometry Namespace Quadrilateral End Namespace End Namespace Inside the new namespace, you can implement the behavior you want. For example, you can create a class. The parent namespace is still its own namespace and can contain any necessary thing. Here is an example: Namespace Geometry Friend Class Triangle Public Base As Double Public Height As Double Public Function Area() As Double Return Base * Height / 2 End Function End Class Namespace Quadrilateral Public Class Rectangle Public Width As Double Public Height As Double Public Function Perimeter() As Double Return (Width + Height) * 2 End Function Public Function Area() As Double Return Width * Height End Function End Class End Namespace End Namespace To access a member of the parent namespace, you can qualify it as we saw previously. To access a member of the nested namespace outside the parent, type the name of the nesting namespace, followed by a period, followed by the name of the nested namespace, followed by a period, and followed by the member you want to access. Here are examples: Namespace Geometry Friend Class Triangle Public Base As Double Public Height As Double Public Function Area() As Double Return Base * Height / 2 End Function End Class Namespace Quadrilateral Public Class Rectangle Public Width As Double Public Height As Double Public Function Perimeter() As Double Return (Width + Height) * 2 End Function Public Function Area() As Double Return Width * Height End Function End Class End Namespace End Namespace Module Exercise
Public Function Main() As Integer Dim Tri As Geometry.Triangle = New Geometry.Triangle Tri.Base = 36.09 Tri.Height = 28.46 MsgBox("Triangle "Base:" & "Height:" "Area:" & Characteristics" vbTab & vbTab & & vbTab & vbTab vbTab & vbTab & & vbCrLf & _ FormatNumber(Tri.Base) & vbCrLf & _ & FormatNumber(Tri.Height) & vbCrLf & _ FormatNumber(Tri.Area()))
Dim Rect As Geometry.Quadrilateral.Rectangle Rect = New Geometry.Quadrilateral.Rectangle Rect.Width = 40.18 Rect.Height = 28.46 MsgBox("Rectangle Characteristics" & vbCrLf & _ "Width:" & vbTab & vbTab & FormatNumber(Rect.Width) & vbCrLf & _ "Height:" & vbTab & vbTab & FormatNumber(Rect.Height) & vbCrLf & _ "Perimeter:" & vbTab & FormatNumber(Rect.Perimeter()) & vbCrLf & _ "Area:" & vbTab & vbTab & FormatNumber(Rect.Area())) Return 0 End Function End Module In the same way: You can create as many namespaces as you want inside of a nesting namespace You can nest as many namespaces in as many nesting namespaces Remember how to backwardly qualify the name of a member of a nested namespace. If the namespace exists in a separate file and you want to import it, type the Imports keyword, followed by the name of the parent namespace, followed by a period, and followed by the nested namespace. In the same way, you can import any nested namespace, as long as you appropriately qualify its name.
Public Function Main() As Integer Console.WriteLine() Return 0 End Function End Module
Home
Besides Read(), the Console class also provides ReadLine(). Like WriteLine(), after performing its assignment, ReadLine() sends the caret to the next line. Otherwise, it plays the same role as the Read() function.
Console.WriteLine("-/- Georgetown Cleaning Services -/-") ' Request customer information from the user Console.Write("Enter Customer Name: ") CustomerName = Console.ReadLine() Console.Write("Enter Customer Phone: ") HomePhone = Console.ReadLine() Console.WriteLine() ' Display the receipt Console.WriteLine("====================================") Console.WriteLine("-/- Georgetown Cleaning Services -/-") Console.WriteLine("====================================") Console.WriteLine("Customer: " + CustomerName) Console.WriteLine("Home Phone: " + HomePhone) Console.WriteLine("====================================") Return 0 End Function End Module 2. To execute the program, press Ctrl + F5 3. Enter the customer name as James Watson 4. Enter the phone number as (410) 493-2005 This would produce: -/- Georgetown Cleaning Services -/Enter Customer Name: James Watson Enter Customer Phone: (410) 493-2005 ==================================== -/- Georgetown Cleaning Services -/==================================== Customer: James Watson Home Phone: (410) 493-2005 ==================================== 5. Return to your programming environment
Number Request
Everything the user types is a string. If you want to get a number from the user, first request a string. Here is an example: Module Module1 Sub Main() Dim Number As Integer Dim strNumber As String Console.Write("Enter a natural number: ") strNumber = Console.ReadLine() End Sub End Module After getting the string, you must convert it to a number. To perform this conversion, you can use one of the conversion functions we mentioned in Lesson 2 for each data type. Here is an example: Module Module1 Sub Main() Dim Number As Integer Dim dblNumber As Integer Dim strNumber As String Console.Write("Enter a natural number: ") strNumber = Console.ReadLine() Number = CInt(strNumber) dblNumber = Number * 2 Console.WriteLine("Number: " + CStr(dblNumber)) End Sub End Module An advanced but faster way to do this is to type Console.ReadLine() in the parentheses of the conversion function. This has the same effect. Here is an example: Module Module1 Sub Main() Dim Number As Integer Dim dblNumber As Integer Console.Write("Enter a natural number: ") Number = CInt(Console.ReadLine()) dblNumber = Number * 2 Console.WriteLine("Number: " + CStr(dblNumber)) End Sub End Module
Console.Write(" ") Console.Write(PriceOneDress) Console.Write(" ") Console.WriteLine(SubTotalDresses) Console.WriteLine("------------------------------------") Console.WriteLine("Total Order: " + CStr(TotalOrder)) Console.WriteLine("Tax Rate: " + CStr(TaxRate * 100) + "%") Console.WriteLine("Tax Amount: " + CStr(TaxAmount)) Console.WriteLine("Net Price: " + CStr(SalesTotal)) Console.WriteLine("------------------------------------") Console.WriteLine("Amount Tended: " + CStr(AmountTended)) Console.WriteLine("Difference: " + CStr(Difference)) Console.WriteLine("====================================") Return 0 End Function End Module 2. Execute the application 3. Enter the requested values. Here is an example of running the program: -/- Georgetown Cleaning Services -/Enter Customer Name: Genevieve Alton Enter Customer Phone: (202) 974-8244 Number of Shirts: 8 Number of Pants: 2 Number of Dresses: 3 The Total order is: 28.711125 Amount Tended? 30 ==================================== -/- Georgetown Cleaning Services -/==================================== Customer: Genevieve Alton Home Phone: (202) 974-8244 -----------------------------------Item Type Qty Unit/Price Sub-Total -----------------------------------Shirts 8 0.95 7.60 Pants 2 2.95 5.90 Dresses 3 4.55 13.65 -----------------------------------Total Order: 27.15 Tax Rate: 5.7500% Tax Amount: 1.561125 Net Price: 28.711125 -----------------------------------Amount Tended: 30 Difference: 1.288875 ==================================== 4. Return to your programming environment
Dim HomePhone As String Dim OrderDate As Date ' Unsigned numbers to represent cleaning items Dim NumberOfShirts As Integer Dim NumberOfPants As Integer Dim NumberOfDresses As Integer ' Each of these sub totals will be used for cleaning items Dim SubTotalShirts As Double Dim SubTotalPants As Double Dim SubTotalDresses As Double ' Values used to process an order Dim TotalOrder As Double Dim TaxAmount As Double Dim SalesTotal As Double Dim AmountTended As Double Dim Difference As Double Console.WriteLine("-/- Georgetown Cleaning Services -/-") ' Request customer information from the user Console.Write("Enter Customer Name: ") CustomerName = Console.ReadLine() Console.Write("Enter Customer Phone: ") HomePhone = Console.ReadLine() Console.WriteLine( & _ "Enter the order date and time (mm/dd/yyyy hh:mm AM/PM)") OrderDate = CDate(Console.ReadLine()) ' Request the quantity of each category of items Console.Write("Number of Shirts: ") Dim strShirts As String = Console.ReadLine() NumberOfShirts = CInt(strShirts) Console.Write("Number of Pants: ") Dim strPants As String = Console.ReadLine() NumberOfPants = CInt(strPants) Console.Write("Number of Dresses: ") Dim strDresses As String = Console.ReadLine() NumberOfDresses = CInt(strDresses) ' Perform the necessary calculations SubTotalShirts = NumberOfShirts * PriceOneShirt SubTotalPants = NumberOfPants * PriceAPairOfPants SubTotalDresses = NumberOfDresses * PriceOneDress ' Calculate the "temporary" total of the order TotalOrder = SubTotalShirts + SubTotalPants + SubTotalDresses ' Calculate the tax amount using a constant rate TaxAmount = TotalOrder * TaxRate ' Add the tax amount to the total order SalesTotal = TotalOrder + TaxAmount ' Communicate the total to the user... Console.Write("\nThe Total order is: ") Console.WriteLine(SalesTotal) ' and request money for the order Console.Write("Amount Tended? ") AmountTended = CDbl(Console.ReadLine()) ' Calculate the difference owed to the customer ' or that the customer still owes to the store Difference = AmountTended - SalesTotal Console.WriteLine() ' Display the receipt Console.WriteLine("====================================") Console.WriteLine("-/- Georgetown Cleaning Services -/-") Console.WriteLine("====================================") Console.WriteLine("Customer: " + CustomerName) Console.WriteLine("Home Phone: " + HomePhone) Console.WriteLine("Date & Time: " + CStr(OrderDate)) Console.WriteLine("------------------------------------") Console.WriteLine("Item Type Qty Unit/Price Sub-Total") Console.WriteLine("------------------------------------") Console.Write("Shirts ") Console.Write(NumberOfShirts) Console.Write(" ") Console.Write(PriceOneShirt) Console.Write(" ") Console.WriteLine(SubTotalShirts) Console.Write("Pants ") Console.Write(NumberOfPants) Console.Write(" ") Console.Write(PriceAPairOfPants) Console.Write(" ") Console.WriteLine(SubTotalPants) Console.Write("Dresses ") Console.Write(NumberOfDresses) Console.Write(" ") Console.Write(PriceOneDress) Console.Write(" ") Console.WriteLine(SubTotalDresses) Console.WriteLine("------------------------------------") Console.WriteLine("Total Order: " + CStr(TotalOrder)) Console.WriteLine("Tax Rate: " + CStr(TaxRate * 100) + "%") Console.WriteLine("Tax Amount: " + CStr(TaxAmount)) Console.WriteLine("Net Price: " + CStr(SalesTotal)) Console.WriteLine("------------------------------------") Console.WriteLine("Amount Tended: " + CStr(AmountTended)) Console.WriteLine("Difference: " + CStr(Difference))
Console.WriteLine("====================================") Return 0 End Function End Module 2. Execute the project 3. Enter the requested values. Here is an example of running the program: -/- Georgetown Cleaning Services -/Enter Customer Name: Alexander Pappas Enter Customer Phone: (301) 397-9764 Enter the order date and time (mm/dd/yyyy hh:mm AM/PM) 06/22/98 08:26 AM Number of Shirts: 2 Number of Pants: 6 Number of Dresses: 0 The Total order is: 20.727000 Amount Tended? 50 ==================================== -/- Georgetown Cleaning Services -/==================================== Customer: Alexander Pappas Home Phone: (301) 397-9764 Date & Time: 6/22/1998 8:26:00 AM -----------------------------------Item Type Qty Unit/Price Sub-Total -----------------------------------Shirts 2 0.95 1.90 Pants 6 2.95 17.70 Dresses 0 4.55 0 -----------------------------------Total Order: 19.60 Tax Rate: 5.7500% Tax Amount: 1.127000 Net Price: 20.727000 -----------------------------------Amount Tended: 50 Difference: 29.273000 ==================================== 4. Return to your programming environment
Full Name: Anselme Bogos Age: 15 Distance: 22.74 As mentioned already, the numeric value typed in the curly brackets of the first part is an ordered number. If you want to display more than one value, provide each incremental value in its curly brackets. The syntax used is: Write("To Display {0} {1} {2} {n}", First, Second, Third, nth ) You can use the sections between a closing curly bracket and an opening curly bracket to create a meaningful sentence.
Console.WriteLine("Customer: {0}", CustomerName) Console.WriteLine("Home Phone: {0}", HomePhone) Console.WriteLine("Date & Time: {0}", OrderDate) Console.WriteLine("------------------------------------") Console.WriteLine("Item Type Qty Unit/Price Sub-Total") Console.WriteLine("------------------------------------") Console.WriteLine("Shirts {0} {1} {2}", _ NumberOfShirts, PriceOneShirt, SubTotalShirts) Console.WriteLine("Pants {0} {1} {2}", _ NumberOfPants, PriceAPairOfPants, SubTotalPants) Console.WriteLine("Dresses {0} {1} {2}", _ NumberOfDresses, PriceOneDress, SubTotalDresses) Console.WriteLine("------------------------------------") Console.WriteLine("Total Order: {0}", TotalOrder) Console.WriteLine("Tax Rate: {0}%", TaxRate * 100) Console.WriteLine("Tax Amount: {0}", TaxAmount) Console.WriteLine("Net Price: {0}", SalesTotal) Console.WriteLine("------------------------------------") Console.WriteLine("Amount Tended: {0}", AmountTended) Console.WriteLine("Difference: {0}", Difference) Console.WriteLine("====================================") Return 0 End Function End Module 2. Execute the program 3. Enter the requested values as done previously 4. Return to your programming environment
Conversion To String
We mentioned earlier that everything the user types using the keyboard is primarily a string and it's your job to convert it to the appropriate type. In reverse, if you have a value that is not a string, you can easily convert it to a string. To support this, we saw in the previous lesson that each data type is equipped with ToString. To convert value of a primitive data type to a string, type the name of the variable, followed by a period, followed, followed by ToString(). Here is an example: Module Module1 Sub Main() Dim FullName As String = "Anselme Bogos" Dim Age As Integer = 15 Dim HSalary As Double = 22.74 Console.WriteLine("Full Name: {0}", FullName) Console.WriteLine("Age: {0}", Age.ToString()) Console.WriteLine("Distance: {0}", HSalary.ToString()) End Sub End Module In some cases, you will type something in the parentheses of ToString().
Number Formatting
To properly display data in a friendly and most familiar way, you can format it. Formatting tells the compiler what kind of data you are using and how you want the compiler to display it to the user. As it happens, you can display a natural number in a common value or, depending on the circumstance, you may prefer to show it as a hexadecimal value. When it comes to doubleprecision numbers, you may want to display a distance with three values on the right side of the decimal separator and in some cases, you may want to display a salary with only 2 decimal places. The System namespace provides a specific letter that you can use in the Write() or WriteLine()'s placeholder for each category of data to display. To format a value, in the placeholder of the variable or value, after the number, type a colon and one of the appropriate letter from the following table. If you are using ToString(), then, in the parentheses of ToString(), you can include a specific letter or combination inside of double-quotes. The letters and their meanings are: Character c d e f g n C D E F G N Used For Currency values Decimal numbers Scientific numeric display such as 1.45e 5 Fixed decimal numbers General and most common type of numbers Natural numbers
R X P
Sub Main() Dim Distance As Double = 248.38782 Dim Age As Integer = 15 Dim NewColor As Integer = 3478 Dim HourlySalary As Double = 22.74 Dim HoursWorked As Double = 35.5018473 Dim WeeklySalary As Double = HourlySalary * HoursWorked Console.WriteLine("Distance: {0}", Distance.ToString("E")) Console.WriteLine("Age: {0}", Age.ToString()) Console.WriteLine("Color: {0}", NewColor.ToString("X")) Console.WriteLine("Weekly Salary: {0} for {1} hours", _ WeeklySalary.ToString("c"), HoursWorked.ToString("F")) End Sub End Module This would produce: Distance: 2.483878E+002 Age: 15 Color: D96 Weekly Salary: $807.31 for 35.50 hours As you may have noticed, if you leave the parentheses of ToString() empty, the compiler would use a default formatting to display the value. As opposed to calling ToString(), you can use the above letters in the curly brackets of the first part of Write() or WriteLine(). In this case, after the number in the curly brackets, type the colon operator followed by the letter.
= = = =
' 5.75%
' Perform the necessary calculations SubTotalShirts = NumberOfShirts * PriceOneShirt SubTotalPants = NumberOfPants * PriceAPairOfPants SubTotalDresses = NumberOfDresses * PriceOneDress ' Calculate the "temporary" total of the order TotalOrder = SubTotalShirts + SubTotalPants + SubTotalDresses ' Calculate the tax amount using a constant rate TaxAmount = TotalOrder * TaxRate ' Add the tax amount to the total order SalesTotal = TotalOrder + TaxAmount ' Communicate the total to the user... Console.Write("\nThe Total order is: ") Console.WriteLine(SalesTotal) ' and request money for the order Console.Write("Amount Tended? ") AmountTended = CDbl(Console.ReadLine()) ' Calculate the difference owed to the customer ' or that the customer still owes to the store Difference = AmountTended - SalesTotal Console.WriteLine() ' Display the receipt Console.WriteLine("====================================") Console.WriteLine("-/- Georgetown Cleaning Services -/-") Console.WriteLine("====================================") Console.WriteLine("Customer: {0}", CustomerName) Console.WriteLine("Home Phone: {0}", HomePhone) Console.WriteLine("Date & Time: {0}", OrderDate) Console.WriteLine("------------------------------------") Console.WriteLine("Item Type Qty Unit/Price Sub-Total") Console.WriteLine("------------------------------------") Console.WriteLine("Shirts {0} {1:C} {2}", _ NumberOfShirts, PriceOneShirt, SubTotalShirts.ToString("C")) Console.WriteLine("Pants {0} {1} {2:C}", _ NumberOfPants, PriceAPairOfPants.ToString("C"), SubTotalPants) Console.WriteLine("Dresses {0} {1:C} {2:C}", _ NumberOfDresses, PriceOneDress, SubTotalDresses) Console.WriteLine("------------------------------------") Console.WriteLine("Total Order: {0:C}", TotalOrder) Console.WriteLine("Tax Rate: {0:P}", TaxRate) Console.WriteLine("Tax Amount: {0}", TaxAmount.ToString("C")) Console.WriteLine("Net Price: {0:F}", SalesTotal) Console.WriteLine("------------------------------------") Console.WriteLine("Amount Tended: {0:C}", AmountTended) Console.WriteLine("Difference: {0:C}", Difference) Console.WriteLine("====================================") Return 0 End Function End Module 2. Save it and switch to the Command Prompt. Then compile the file and execute the application. Here is an example: -/- Georgetown Cleaning Services -/Enter Customer Name: Gretchen McCormack Enter Customer Phone: (410) 739-2884 Enter the order date and time (mm/dd/yyyy hh:mm AM/PM) 04/09/2001 10:25 AM Number of Shirts: 5 Number of Pants: 12 Number of Dresses: 8 The Total order is: 80.951625 Amount Tended? 100 ==================================== -/- Georgetown Cleaning Services -/==================================== Customer: Gretchen McCormack Home Phone: (410) 739-2884 Date & Time: 4/9/2001 10:25:00 AM -----------------------------------Item Type Qty Unit/Price Sub-Total -----------------------------------Shirts 5 $0.95 $4.75 Pants 12 $2.95 $35.40 Dresses 8 $4.55 $36.40 -----------------------------------Total Order: $76.55 Tax Rate: 5.75 % Tax Amount: $4.40 Net Price: 80.95 -----------------------------------Amount Tended: $100.00 Difference: $19.05 ==================================== 3. Return to your programming environment
Line Formatting
In the above programs, to display a line of text, we easily used Write() or WriteLine(). To position text of different lengths one above the other, we had to "corrupt" a string by including extra-empty spaces. Such a technique is uncertain and less professional. Fortunately, you can highly format how a string or a line of text should display. The .NET Framework provides mechanisms to control the amount of space used to display a string of text and how to align that string on its line. To specify the amount of space used to display a string, you can use its placeholder in Write() or WriteLine(). To do this, in the placeholder, type the 0 or the incrementing number of the placer and its formatting character if necessary and if any. Then, type a comma followed by the number of characters equivalent to the desired width. Here are examples: Module Module1 Sub Main() Dim FullName As String = "Anselme Bogos" Dim Age As Integer = 15 Dim HourlySalary As Double = 22.74 Console.WriteLine("Full Name: {0,20}", FullName) Console.WriteLine("Age:{0,14}", Age.ToString()) Console.WriteLine("Distance: {0:C,8}", HourlySalary.ToString()) End Sub End Module This would produce: Full Name: Anselme Bogos Age: 15 Distance: 22.74 The sign you provide for the width is very important. If it is positive, the line of text is aligned to the right. This should be your preferred alignment for numeric values. If the number is negative, then the text is aligned to the left.
= = = =
' 5.75%
Console.Write("Number of Shirts: ") Dim strShirts As String = Console.ReadLine() NumberOfShirts = CInt(strShirts) Console.Write("Number of Pants: ") Dim strPants As String = Console.ReadLine() NumberOfPants = CInt(strPants) Console.Write("Number of Dresses: ") Dim strDresses As String = Console.ReadLine() NumberOfDresses = CInt(strDresses) ' Perform the necessary calculations SubTotalShirts = NumberOfShirts * PriceOneShirt SubTotalPants = NumberOfPants * PriceAPairOfPants SubTotalDresses = NumberOfDresses * PriceOneDress ' Calculate the "temporary" total of the order TotalOrder = SubTotalShirts + SubTotalPants + SubTotalDresses ' Calculate the tax amount using a constant rate TaxAmount = TotalOrder * TaxRate ' Add the tax amount to the total order SalesTotal = TotalOrder + TaxAmount ' Communicate the total to the user... Console.Write("\nThe Total order is: ") Console.WriteLine(SalesTotal) ' and request money for the order Console.Write("Amount Tended? ") AmountTended = CDbl(Console.ReadLine()) ' Calculate the difference owed to the customer ' or that the customer still owes to the store Difference = AmountTended - SalesTotal Console.WriteLine() ' Display the receipt Console.WriteLine("====================================") Console.WriteLine("-/- Georgetown Cleaning Services -/-") Console.WriteLine("====================================") Console.WriteLine("Customer: {0}", CustomerName) Console.WriteLine("Home Phone: {0}", HomePhone) Console.WriteLine("Order Date: {0:D}", OrderDate) Console.WriteLine("Order Time: {0:t}", OrderTime) Console.WriteLine("------------------------------------") Console.WriteLine("Item Type Qty Unit/Price Sub-Total") Console.WriteLine("------------------------------------") Console.WriteLine("Shirts {0} {1:C} {2}", _ NumberOfShirts, PriceOneShirt, SubTotalShirts.ToString("C")) Console.WriteLine("Pants {0} {1} {2}", _ NumberOfPants, PriceAPairOfPants, SubTotalPants) Console.WriteLine("Dresses {0} {1:C} {2:C}", _ NumberOfDresses, PriceOneDress, SubTotalDresses) Console.WriteLine("------------------------------------") Console.WriteLine("Total Order: {0:C}", TotalOrder) Console.WriteLine("Tax Rate: {0:P}", TaxRate) Console.WriteLine("Tax Amount: {0}", TaxAmount.ToString("C")) Console.WriteLine("Net Price: {0:F}", SalesTotal) Console.WriteLine("------------------------------------") Console.WriteLine("Amount Tended: {0:C}", AmountTended) Console.WriteLine("Difference: {0:C}", Difference) Console.WriteLine("====================================") Return 0 End Function End Module 2. Save, compile, and run the program. Here is an example: -/- Georgetown Cleaning Services -/Enter Customer Name: Antoinette Calhoun Enter Customer Phone: (703) 797-1135 Enter the order date(mm/dd/yyyy): 04/12/2002 Enter the order time(hh:mm AM/PM): 2:12 PM Number of Shirts: 5 Number of Pants: 2 Number of Dresses: 1 The Total order is: $16.07 Amount Tended? 20 ==================================== -/- Georgetown Cleaning Services -/==================================== Customer: Antoinette Calhoun Home Phone: (703) 797-1135 Order Date: Friday, April 12, 2002 Order Time: 2:12 PM -----------------------------------Item Type Qty Unit/Price Sub-Total -----------------------------------Shirts 5 $0.95 $4.75 Pants 2 $2.95 $5.90 Dresses 1 $4.55 $4.55 -----------------------------------Total Order: $15.20 Tax Rate: 5.75 % Tax Amount: $0.87
Net Price: $16.07 -----------------------------------Amount Tended: $20.00 Difference: $3.93 ==================================== 3. Return to your programming environment
Previous
Next
Custom Libraries
Introduction
If you cannot find a function you want, you can create one and be able to use it. If you plan to use such a function over and over again in different programs, you can create a library and store the function in it. You can even create one or a series of commercial functions and be able to distribute or sell it through a library. A library is a program that contains procedures and/or other resources that other programs can use. Such a program is created with the same approach as the programs we have created so far. Because a library is not an executable, it does not need the Main() procedure. A library usually has the extension .dll.
Creating a Library
A library can be made of a single file or as many files as necessary. A file that is part of a library can contain one or more procedures (or classes). Each procedure (or class) should implement a behavior that can eventually be useful and accessible to other procedures (or classes). The contents of a library are created exactly like those we have used so far. Everything depends on how you compile it. To create a library: On the main menu of Microsoft Visual Studio, you can click File -> New -> Project On the Start Page, on the right side of Create, you can click Project On the Standard toolbar, you can click the New Project button or click the arrow of the New Project button and click New Project In the Templates list of the New Project dialog box, click Class Library. Accept or specify the name and click OK. Once the starting project has been generated, write the necessary code. To compile it, on the main menu, click Build -> Build Solution. If you were working from the command prompt, you would execute the following command: vbc /target:library NameOfFile.vb After doing this, a library with the name of the file and the extension .dll would be created. If you use the above technique, the new library would be created using the name of the file. If you are working from the Command Prompt, to compile the project and create a custom name, use the following syntax: vbc /target:library /out:DesiredNameOfLibrary.dll NameOfFile.vb Here is an example: vbc /target:library /out:Arithmetic.dll exo.vb
Public Class Arithmetic Function Add(ByVal x As Double, ByVal y As Double) As Double Return x + y End Function Function Subtract(ByVal x As Double, ByVal y As Double) As Double Return x - y End Function Function Multiply(ByVal x As Double, ByVal y As Double) As Double Return x * y End Function
Function Divide(ByVal x As Double, ByVal y As Double) As Double If y = 0 Then Return 0 Return x / y End Function End Class 8. To create the library, on the main menu, click Build -> Build Arithmetic 9. To start another project, on the main menu, click File -> New -> Project... 10. In the Templates List, click Console Application 11. Change the Name to Algebra and click OK 12. In Windows Explorer or My Documents, locate the Arithmetic folder that contains the library project. Access a sub-folder of the same name, followed by the bin sub-folder, and followed by the Debug sub-folder 13. Right-click Arithmetic.dll and click Copy 14. Still in Windows Explorer or My Documents, locate the Algebra folder that contains the current project. Right-click the sub-folder of the same name and click Paste 15. In the Solution Explorer, right-click Algebra and click Add Reference... 16. In the Add Reference dialog box, click the Browse tab 17. Use the Look In combo box to locate and select a sub-folder named Algebra in the current project 18. Click Arithmetic.dll and click OK 19. In the Solution Explorer, right-click Module1.vb and click Rename 20. Type Exercise.vb and press Enter. Accept to make all necessary changes 21. Change the the file as follows:
Imports Operations Module Exercise Public Function Main() As Integer Dim Result As Double Dim Oper As Arithmetic Dim Number1 As Double, Number2 As Double Number1 = 244.58 Number2 = 5082.88 Oper = New Arithmetic Result = Oper.Add(Number1, Number2) MsgBox(Number1 & " + " & Number2 & " = " & Result) Return 0 End Function End Module 22. To execute the project, on the main menu, click Debug -> Start Without Debugging
Home
Error Handling
Introduction to Errors
Overview
We always want to create a problem-free application, one that always behaves as expected. In reality, many things can go wrong while a program is running. As an application developer, you should predict as many bad behaviors as possible so you can take appropriate actions. To assist you with dealing with errors, the Visual Basic language provides many keywords, operators, and techniques.
follows: Module Exercise Public Function Main() As Integer Dim HourlySalary As Double Dim WeeklySalary As Double ' The following line may produce an error, such as ' if the user types an invalid number HourlySalary = CDbl(InputBox("Enter the employee's hourly salary:")) ' If there was an error, the flow would jump to the label WeeklySalary = HourlySalary * 40 Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary)) Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary)) Exit Function ThereWasAProblem: Console.WriteLine("An error occurred when the application executed") Return 0 End Function End Module Here is an example of running the program: Hourly Salary: 15.85 Weekly Salary: 634.00 Press any key to continue . . .
In Case of Error
Jump to a Label
We saw that you can create a label that would present a message to the user when a problem happens. Before an error occurs, you would indicate to the compiler where to go if an error occurs. To provide this information, under the line that starts the procedure, type an On Error GoTo expression followed by the name of the label where you created the message. Here is an example: Module Exercise Public Function Main() As Integer On Error GoTo ThereWasAProblem Dim HourlySalary As Double Dim WeeklySalary As Double ' The following line may produce an error, such as ' if the user types an invalid number HourlySalary = CDbl(InputBox("Enter the employee's hourly salary:")) ' If there was an error, the flow would jump to the label WeeklySalary = HourlySalary * 40 Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary)) Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary)) Exit Function ThereWasAProblem: Console.WriteLine("An error occurred when the application executed") Return 0 End Function End Module The On Error GoTo indicates to the compiler where to transfer code if an error occurs. Here is an example of running the program:
An error occurred when the application executed Press any key to continue . . .
Go to a Numbered Label
Instead of defining a lettered label where to jump in case of error, you can create a numeric label: Module Exercise
Public Function Main() As Integer Dim HourlySalary As Double Dim WeeklySalary As Double ' The following line may produce an error, such as ' if the user types an invalid number HourlySalary = CDbl(InputBox("Enter the employee's hourly salary:")) ' If there was an error, the flow would jump to the label WeeklySalary = HourlySalary * 40 Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary)) Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary)) Exit Function 28: Console.WriteLine("An error occurred when the application executed") Return 0 End Function End Module After creating the numeric label, you can ask the compiler to jump to it if a problem occurs. To do this, type On Error GoTo followed by the numeric label. The compiler would still jump to it when appropriate. Here is an example: Module Exercise Public Function Main() As Integer On Error GoTo 28 Dim HourlySalary As Double Dim WeeklySalary As Double ' The following line may produce an error, such as ' if the user types an invalid number HourlySalary = CDbl(InputBox("Enter the employee's hourly salary:")) ' If there was an error, the flow would jump to the label WeeklySalary = HourlySalary * 40 Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary)) Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary)) Exit Function 28: Console.WriteLine("An error occurred when the application executed") Return 0 End Function End Module This version of the program would behave like the previous one and produce the same result. Notice that the numeric label works like the lettered label. In other words, before writing the On Error GoTo expression, you must have created the label. In reality, this is not a rule. You can ask the compiler to let you deal with the error one way or another. To do this, use the On Error GoTo 0 or On Error GoTo -1 expression. Here is an example: Module Exercise Public Function Main() As Integer On Error GoTo 0 Dim HourlySalary As Double Dim WeeklySalary As Double ' The following line may produce an error, such as ' if the user types an invalid number HourlySalary = CDbl(InputBox("Enter the employee's hourly salary:")) ' If there was an error, the flow would jump to the label WeeklySalary = HourlySalary * 40 Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary)) Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary)) Return 0 End Function End Module In this case, if/when the error occurs, you must have a way to deal with it.
use the Resume operator. It presents many options. After an error has occurred, to ask the compiler to proceed with the regular flow of the program, type the Resume keyword. Here is an example: Module Exercise Public Function Main() As Integer On Error GoTo ThereWasAProblem Dim HourlySalary As Double Dim WeeklySalary As Double ' The following line may produce an error, such as ' if the user types an invalid number HourlySalary = CDbl(InputBox("Enter the employee's hourly salary:")) ' If there was an error, the flow would jump to the label WeeklySalary = HourlySalary * 40 Resume Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary)) Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary)) Exit Function ThereWasAProblem: Console.WriteLine("An error occurred when the application executed") Return 0 End Function End Module Notice that you can write the Resume operator almost anywhere. In reality, you should identify where the program would need to resume. If you want the program to continue with an alternate value than the one that caused the problem, in the label section, type Resume Next. Here is an example: Module Exercise Public Function Main() As Integer On Error GoTo ThereWasAProblem Dim HourlySalary As Double Dim WeeklySalary As Double ' The following line may produce an error, such as ' if the user types an invalid number HourlySalary = CDbl(InputBox("Enter the employee's hourly salary:")) ' If there was an error, the flow would jump to the label WeeklySalary = HourlySalary * 40 Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary)) Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary)) Exit Function ThereWasAProblem: Console.WriteLine("An error occurred when the application executed") Resume Next Return 0 End Function End Module We know that in our code, there was probably a problem, which is the reason we presented a message to the user. Then, when code resumes, where should the compiler go? After all, the problem was not solved. One way you can deal with the problem is to provide an alternative to what caused the problem, since you are supposed to know what type of problem occurred. In the case of an arithmetic calculation, imagine we know that the problem was caused by the user typing an invalid number (such as typing a name where a number was expected). Instead of letting the program crash, we can provide an alternate number. The easiest number is 0. Before asking the compiler to resume, to provide an alternative solution (a number in this case), you can re-initialize the variable that caused the error. Here is an example: Module Exercise Public Function Main() As Integer On Error GoTo ThereWasAProblem Dim HourlySalary As Double Dim WeeklySalary As Double ' The following line may produce an error, such as ' if the user types an invalid number HourlySalary = CDbl(InputBox("Enter the employee's hourly salary:")) ' If there was an error, the flow would jump to the label WeeklySalary = HourlySalary * 40
Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary)) Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary)) Exit Function ThereWasAProblem: Console.WriteLine("An error occurred when the application executed") HourlySalary = 0 Resume Next Return 0 End Function End Module If there are many variables involved, as is the case for us, you can initialize each. Here an example: Module Exercise Public Function Main() As Integer On Error GoTo ThereWasAProblem Dim HourlySalary As Double, WeeklyTime As Double Dim WeeklySalary As Double ' One of these two lines could produce an error, such as ' if the user types an invalid number HourlySalary = CDbl(InputBox("Enter the employee's hourly salary:")) WeeklyTime = CDbl(InputBox("Enter the time worked for the week:")) ' If there was an error, the flow would jump to the label WeeklySalary = HourlySalary * WeeklyTime Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary)) Console.WriteLine("Weekly Time: {0}", FormatNumber(WeeklyTime)) Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary)) Exit Function ThereWasAProblem: Console.WriteLine("An error occurred when the application executed") HourlySalary = 0 WeeklyTime = 0 Resume Next Return 0 End Function End Module Here is an example of running the program:
Hourly Salary: 20.85 Weekly Time: 42.50 Weekly Salary: 886.13 Press any key to continue . . . Here is another example of running the program:
An error occurred when the application executed Hourly Salary: 0.00 Weekly Time: 38.00 Weekly Salary: 0.00 Press any key to continue . . . Here is one more example of running the program:
An error occurred when the application executed An error occurred when the application executed Hourly Salary: 0.00 Weekly Time: 0.00 Weekly Salary: 0.00 Press any key to continue . . .
Types of Error
Introduction
In our introductions to errors, we mostly anticipated only problems related to arithmetic calculations. In reality, a program can face various categories of bad occurrences. The more problems you prepare for, the least headaches you will have. Problems are divided in two broad categories.
Syntax Errors
A syntax error occurs if your code tries to perform an operation that the Visual Basic language does not allow. These errors are probably the easiest to locate because the Code Editor is configured to point them out at the time you are writing your code. If you try typing or try inserting an operator or keyword in the wrong place on your code, the Code Editor would point it out by underlining it. Here is an example:
In this case, if you were trying to use the Do keyword instead of a data type (probably Double in
this case), the Code Editor would show it right away. This type of error is pointed out for every keyword and operator you try to use. Notice that, in the above example, we used a valid keyword but at the wrong time. If you mistype a keyword or an operator, you would receive an error. Fortunately, the Code Editor is equipped to know all keywords of the Visual Basic language. Consider the following example:
The programmer mistyped the Mod operator and wrote MAD instead. If you forget to include a necessary factor in your code, you would get a syntax error. For example, if you are creating a binary arithmetic expression that expects a second operand after the operator, you would receive an error. Here is an example:
In this case, the programmer pressed Enter after the Mod operator, as if the expression was complete. This resulted in an error. These are just a few types of syntax errors you may encounter. As mentioned already, if you use the Code Editor to write your code, most of these errors are easy to detect and fix.
Run-Time Errors
A run-time error occurs when an application tries to do something that the operating system does not allow. In some cases, only your application would crash. In some other cases, the user may receive a more serious error. As its name indicates, a run-time error occurs when the program runs; that is, after you have created your application. Fortunately, during the testing phase, you may encounter some of the errors so you can fix them before distributing your application. Some other errors may not occur even if you test your application. They may occur to the users after you have distributed your application. For example, you can create a car rental application that is able to display pictures 100% of the time on your computer while locating them from the E: drive. Without paying attention, after distributing your application, the user's computer may not have an E: drive and, when trying to display the pictures, the application may crash. Examples of run-time errors are: a. Trying to use computer memory that is not available b. Performing a calculation that the computer hardware (for example the processor) does not allow. An example is division by 0 (the Intel and AMD processors are equipped not to allow
division by 0) c. Trying to use or load a library that is not available or is not accessible, for any reason d. Performing an arithmetic operation on two incompatible types (such as trying to assign to an Integer variable the result of adding a string to a Double value) e. Using a loop that was not properly initialized f. Trying to access a picture not accessible. Maybe the path specified for the picture is wrong. Maybe your code gives the wrong extension to the file, even though the file exists g. Accessing a value beyond the allowable range. For example, using a Byte variable to assign a performed operation that produces a value the variable cannot hold As you may imagine, because run-time errors occur after the application has been described as ready, some of these errors can be difficult to identify. Some other errors depend on the platform that is running the application (the operating system, the processor, the version of the application, the (available) memory, etc).
Module Exercise Public Function Main() As Integer On Error GoTo ThereWasAProblem Dim HourlySalary As Double, WeeklyTime As Double Dim WeeklySalary As Double ' One of these two lines could produce an error, such as ' if the user types an invalid number HourlySalary = CDbl(InputBox("Enter the employee's hourly salary:")) WeeklyTime = CDbl(InputBox("Enter the time worked for the week:")) ' If there was an error, the flow would jump to the label WeeklySalary = HourlySalary * WeeklyTime Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary)) Console.WriteLine("Weekly Time: {0}", FormatNumber(WeeklyTime)) Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary)) Exit Function ThereWasAProblem: If Err.Number = 13 Then MsgBox("You typed an invalid value") HourlySalary = 0 WeeklyTime = 0 Resume Next End If Return 0 End Function End Module Here is an example of running the program:
Hourly Salary: 0.00 Weekly Time: 38.50 Weekly Salary: 0.00 Press any key to continue . . .
Hourly Salary: 0.00 Weekly Time: 40.00 Weekly Salary: 0.00 Press any key to continue . . . In some cases, the error message will not be explicit enough, especially if a user simply reads it to you over the phone. The alternative is to create your own message in the language you easily understand, as we did earlier. If you want, you can also display a message that combines the Err.Description message and your own message. Here is an example: Module Exercise Public Function Main() As Integer On Error GoTo ThereWasAProblem Dim HourlySalary As Double, WeeklyTime As Double Dim WeeklySalary As Double ' One of these two lines could produce an error, such as ' if the user types an invalid number HourlySalary = CDbl(InputBox("Enter the employee's hourly salary:")) WeeklyTime = CDbl(InputBox("Enter the time worked for the week:")) ' If there was an error, the flow would jump to the label WeeklySalary = HourlySalary * WeeklyTime Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary)) Console.WriteLine("Weekly Time: {0}", FormatNumber(WeeklyTime)) Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary)) Exit Function ThereWasAProblem: If Err.Number = 13 Then MsgBox(Err.Description & ": The value you typed cannot be accepted.") HourlySalary = 0 WeeklyTime = 0 Resume Next End If Return 0 End Function End Module
Previous
Home
Events
Introduction
In a typical application, every class is mostly meant to interact with others, either to request values and methods of the other classes or to provide other classes with some values or a behavior they need. When a class A requests a value or service from another class B, class A is referred to as a client of class B. This relationship is important not simply because it establishes a relationship between both classes but also because class B should be ready to provide the value or behavior that a client needs at a certain time. While a class B is asked to provide some values to, or perform some assignment(s) for, another class A, many things would happen. In fact, there is an order that the actions should follow. For example, during the lifetime of a program, that is, while a program is running, a class may be holding a value it can provide to its client but at another time, that value may not be available anymore, for any reason; nothing strange, this is just the ways it happens. Because different things can happen to a class B while a program is running, and because only class B would be aware of these, it must be able to signal to the other classes when there is a change. This is the basis of events: An event is an action that occurs on an object and affects it in a way that its clients must be made aware of.
Event Creation
An event is declared like a pseudo-procedure. To actually declare an event, you use the Event keyword with the following formula: [modifier] Event Name(Argument) The modifier can be Public, Private, Protected, or Friend. The Event keyword is required. It is followed by a name for the event. If the event has arguments, enter them in its parentheses. Here is an example that declares an event: Module Exercise Private Event Evidence() End Module
Raising an Event
To use an event, the object that causes it must initiate it. When this happens, the object is said to raise the event. To assist you with this, the Visual Basic language provides the RaiseEvent operator. To use it, the formula to follow is: RaiseEvent EventName(Argument(s)) You start with the RaiseEvent keyword followed by the name of the event you would have declared previously. The name of the event is followed by parentheses. Here is an example: Module Exercise Private Event Evidence() Public Function Main() As Integer RaiseEvent Evidence() Return 0 End Function End Module
Module Exercise Private Sub ShowMessage() MsgBox("Get the necessary message") End Sub End Module To add a handler to the program, you use the AddHandler operator with the following formula: AddHandler EventName, AddressOf Procedure The AddHandler and the AddressOf operators are required. The EventName placeholder is used to specify the name of the event that is being dealt with. The Procedure factor is the name of the procedure that will implement the event. Here is an example: Module Exercise Delegate Sub Messenger() Private Event Evidence As Messenger Private Sub ShowMessage() MsgBox("Get the necessary message") End Sub Public Function Main() As Integer AddHandler Evidence, AddressOf ShowMessage Return 0 End Function End Module
Raising an Event
After adding a handler to the event, it is ready but you must launch its action. To do this, you can use the RaiseEvent operator with the following formula: RaiseEvent EventName() The RaiseEvent operator is required. The EventName placeholder is used to specify the name of the event, and it must be followed by parentheses. Here is an example: Module Exercise Delegate Sub Messenger() Private Event Evidence As Messenger Private Sub ShowMessage() MsgBox("Get the necessary message") End Sub Public Function Main() As Integer AddHandler Evidence, AddressOf ShowMessage RaiseEvent Evidence() Return 0 End Function End Module
A Parameterized Event
The event we used in the previous sections did not take any argument. Just like a delegate, an event can take an argument. The primary rule to follow is that both its delegate and the procedure associated with it must take the same type of event. The second rule is that, when raising the event, you must pass an appropriate event to it. Here is an example: Module Exercise Delegate Sub Messenger(ByVal Msg As String) Private Event Evidence As Messenger Private Sub ShowMessage(ByVal ToShow As String) MsgBox(ToShow) End Sub Public Function Main() As Integer AddHandler Evidence, AddressOf ShowMessage RaiseEvent Evidence("Is this the last thing to do?") Return 0 End Function End Module Just like an event can take an argument, it can also take more than one argument. The primary rules are the same as those for a single parameter. You just have to remember that you are dealing with more than one argument. Here is an example: Module Exercise Delegate Sub Messenger(ByVal Originator As String, ByVal Msg As String) Private Event Evidence As Messenger Private Sub ShowMessage(ByVal Sender As String, ByVal ToShow As String)
MsgBox(Sender & ": " & ToShow) End Sub Public Function Main() As Integer AddHandler Evidence, AddressOf ShowMessage RaiseEvent Evidence("Message form the Accounting Department", _ "Remember to do your time sheet") Return 0 End Function End Module Instead of a parameter of a primitive type, you can create an event that takes a class as argument.
Home
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).
MsgBox(Summary) Return 0
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:
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:
3. Notice the yellow arrow button in the margin. Notice that the Locals window displays the name of the Main function and the variables in the
function. To end debugging, on the main menu, click Debug -> Stop Debugging 4. Change the code as follows: Module LoanEvaluation Public Function Main() As Integer Dim Summary As String Dim Principal As Double Dim InterestRate As Double Dim Period As Double Dim InterestAmount As Double Dim FutureValue As Double Summary = "This application allows you to evaluate a loan." & vbCrLf Summary += "To proceed, enter the following values" & vbCrLf MsgBox(Summary, MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, "Watts A Loan?") Principal = CDbl(InputBox("Enter the principal: ", "Watts A Loan?", "0.00")) InterestRate = CDbl(InputBox("Enter the interest rate: ", "Watts A Loan?", "0.00")) / 100 Period = CDbl(InputBox("Enter the number of months: ", "Watts A Loan?", "0.00")) / 12 InterestAmount = Principal * InterestRate * Period FutureValue = Principal + InterestAmount Summary Summary Summary Summary Summary vbCrLf Summary += "Interest Rate:" & vbTab & InterestRate.ToString("P") & vbCrLf Summary += "Period:" & vbTab & vbTab & CStr(Period * 12) & " months" & vbCrLf Summary += "Interest Amount:" & vbTab & InterestAmount.ToString("F") & vbCrLf Summary += "Future Value:" & vbTab & FutureValue.ToString("F") & vbCrLf Summary += "========================" MsgBox(Summary, MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, "Watts A Loan?") Return 0 End Function End Module 5. To restart debugging, on the main menu, click Debug -> Step Into. Notice that the Locals window displays a list of the local variables and their starting values: = "Watts A Loan?" & vbCrLf += "========================" & vbCrLf += "Loan Summary" & vbCrLf += "-------------------------------------" & vbCrLf += "Principal:" & vbTab & vbTab & Principal.ToString("F") &
6. To continue debugging, on the Standard toolbar, click the Step Into button 7. To continue debugging, press F8 twice
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
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
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.
2. On the main menu, click Debug -> Start Debugging 3. Click OK on the message box 4. When asked, enter the values as follows and press Enter after each Principal Interest Rate Period 1500 15.55 24
5. Press F5 to continue
6. In the Code Editor, click the FutureValue = Principal + InterestAmount line 7. On the main menu, click Debug -> Toggle Breakpoint 8. In the Code Editor, click the Principal = CDbl(InputBox("Enter the principal: ", line 9. On the main menu, click Debug -> Toggle Breakpoint 10. In the Code Editor, right-click the Summary = "Watts A Loan?" & vbCrLf line, position the mouse on Breakpoints, and click Insert Breakpoint
11. To execute, press F5 12. Click OK on the message box. Notice the first breakpoint has changed
13. To continue, press F5 14. When asked, enter the values as follows and press Enter after each Principal Interest Rate Period 17500 9.75 48
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.
End Function Public Function Main() As Integer Dim Principal As Double Dim InterestRate As Double Dim Period As Double Dim InterestAmount As Double Dim FutureValue As Double Announce() Principal = GetPrincipal() InterestRate = GetInterestRate() Period = GetPeriod() Return 0 End Function End Module 2. To debug, on the main menu, click Debug -> Step Into. Notice that the yellow button is positioned in the margin on the left of the Main() function 3. To continue debugging, on the Standard toolbar, click the Step Into button 4. Click OK on the message box 5. Click the Step Into button again two times. Notice the yellow margin button is positioned on Principal = GetPrincipal() 6. Click the Step Into button and notice that the yellow-point button is positioned on the starting point of the GetPrincipal() function 7. Click the Step Into button again. Notice that the debugging is continuing in the body of the GetPrincipal() function and visits each line 8. Click the Step Into button function again three times to complete debugging the GetPrincipal() four times
9. To stop the debugging, on the Standard toolbar, click the Stop Debugging button 10. To debug, on the main menu, click Debug -> Step Into. Notice that the yellow button is positioned in the margin 11. To continue, on the Standard toolbar, click the Step Into button 12. Click OK on the message box 13. Click the Step Into button twice until the yellow margin button is positioned on the Principal = GetPrincipal() line 14. To skip the GetPrincipal() function, on the main menu, click Debug -> Step Over. Notice that, this time, the body of the GetPrincipal() function is skipped 15. Click the Step Into button 16. To stop the debugging, on the main menu, click Debug -> Stop Debugging 17. Change the document as follows: Module LoanEvaluation Private Sub Announce() MsgBox("This application allows you to evaluate a loan." & vbCrLf & "To proceed, enter the following values" & vbCrLf, MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, "Watts A Loan?") End Sub Private Function GetPrincipal() As Double Dim PresentValue As Double PresentValue = CDbl(InputBox("Enter the principal: ", "Watts A Loan?", "0.00")) Return PresentValue End Function Private Function GetInterestRate() As Double Dim Rate As Double Rate = CDbl(InputBox("Enter the interest rate: ", "Watts A Loan?", "0.00")) Return Rate End Function Private Function GetPeriod() As Integer Dim Months As Integer Months = CDbl(InputBox("Enter the number of months: ", "Watts A Loan?", "0.00")) Return Months four times
End Function Private Sub ShowSummary(ByVal Principal As Double, ByVal AnnualRate As Double, ByVal Periods As Integer, ByVal InterestCollected As Double, ByVal TotalCollected As Double) MsgBox("Watts A Loan?" & vbCrLf & "========================" & vbCrLf & "Loan Summary" & vbCrLf & "-------------------------------------" & vbCrLf & "Principal:" & vbTab & vbTab & Principal.ToString("F") & vbCrLf & "Interest Rate:" & vbTab & AnnualRate.ToString("P") & vbCrLf & "Period:" & vbTab & vbTab & CStr(Periods * 12) & " months" & vbCrLf & "Interest Amount:" & vbTab & InterestCollected.ToString("F") & vbCrLf & "Future Value:" & vbTab & TotalCollected.ToString("F") & vbCrLf & "========================", MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, "Watts A Loan?") End Sub Public Function Main() As Integer Dim Principal As Double Dim InterestRate As Double Dim Period As Double Dim InterestAmount As Double Dim FutureValue As Double Announce() Principal = GetPrincipal() InterestRate = GetInterestRate() / 100 Period = GetPeriod() / 12 InterestAmount = Principal * InterestRate * Period FutureValue = Principal + InterestAmount ShowSummary(Principal, InterestRate, Period, InterestAmount, FutureValue) Return 0 End Function End Module 18. To debug, on the Standard toolbar, click the Step Into button 19. To continue, press F8 four times 20. Click OK on the message box 21. Press F8 two times and notice the yellow margin button is positioned on Principal = GetPrincipal() 22. Press F8 to start debugging the GetPrincipal() function 23. Press F8 and notice that the debugging is continuing in the body of the GetPrincipal() function line by line 24. When asked for the principal, type 21650 and press Enter 25. Press F8 twice 26. To stop the debugging, on the Standard toolbar, click the Stop Debugging button 27. To debug again, press F8 five times 28. Click OK on the message box 29. Click the Step Into button twice until the yellow margin button is positioned on the Principal = GetPrincipal() line 30. To avoid debugging line after line in the GetPrincipal() function, on the main menu, click Debug -> Step Over 31. When asked to give the principal, type 3600 and press Enter 32. Click the Step Into button 33. Keep pressing the Step Over button 34. When asked to provide the interest rate, type 14.05 and press Enter 35. Continue stepping over 36. When asked to provide the number of months, type 48 and press Enter 37. Continue stepping over to the end 38. On the main menu, click Debug -> Delete All Breakpoints 39. On the main menu, click File -> Close Project or File -> Close Solution 40. When asked whether you want to save, click Discard
Home
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
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.
2. Notice that the debugging yellow arrow indicator is positioned on the left of the Main() function. To continue debugging, on the main menu, click Debug -> Step Into 3. Again, on the main menu, click Debug -> Step Into 4. Read the message box and click OK 5. Press F8 three times until a message box comes up 6. Click OK on the message box. Notice that the debugging gets in the body of the IdentifyEmployee() function 7. To continue, press F8 Notice that the debugger jumps to the Employee.vb file 8. In the Locals window, click the + button of Me to expand it. Notice that it shows the member variables of the class
9. To continue debugging, on the Standard toolbar, click the Step Into button debug the Employee class and observe the values in the Locals window 11. Press F8 and notice that the IdentifyEmployee() function gets focus 12. Press F8 again twice 13. When requested, enter the Employee # as 80226 and click OK 14. Click the Step Into button 15. When asked for the first name, type David and click OK 16. Press F8 17. For the last name, type Boyton and click OK 18. Press F8 19. For the title, type Shift Supervisor and click OK. Observe the values in the Locals window
continually to
10. Continue stepping into until the debugger switches back to the LoanEvaluation.vb file
20. Press F8 a few times until the debugger gets to the Client = IdentifyCustomer() line 21. To continue, press F8 and observe the debugging 22. Click OK on the message box 23. Continue pressing F8 until the Customer.vb file gets focus 24. Continue pressing F8 until focus gets back to the LoanEvaluation.vb file 25. In the Locals window, click the + button of Me to expand it
26. Press F8 to continue debugging 27. When asked for the customer name, type Ann Nanze and click OK 28. Press F8 29. When asked for the phone number, type (106) 042-8636 and click OK 30. To continue debugging, press F8 a few times until a message box comes up 31. Read the message box and click OK 32. Press F8 to continue 33. In the Locals window, click the + button
34. Press F8 twice 35. When the principal is requested, type 1000 and click OK 36. Press F8 37. For the interest rate, type 16.05 and click OK 38. Press F8 39. For the period, enter 12 and click OK
40. Press F8 41. In the Locals window, click the second + button
42. On the Standard toolbar, click the Step Into button 43. In the Locals window, expand the nodes
44. Press F8 45. In the Locals window, expand the las + node to see the current values of the variables
46. Keep pressing F8 continually. Observe the evolution in the Code Editor and the values in the Locals window 47. When the message box comes up, review it and click OK
48. On the main menu, click File -> Close Solution or File -> Close Project 49. When asked whether you want to save, click Discard
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.
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.
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
> 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.
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
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
Home
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.
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.
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
Home
' 5.75%
SubTotalPants = Order.NumberOfPants * PriceAPairOfPants SubTotalDresses = Order.NumberOfDresses * PriceOneDress ' Calculate the "temporary" total of the order TotalOrder = SubTotalShirts + SubTotalPants + SubTotalDresses ' Calculate the tax amount using a constant rate TaxAmount = TotalOrder * TaxRate ' Add the tax amount to the total order SalesTotal = TotalOrder + TaxAmount ' Communicate the total to the user... Console.WriteLine(vbcrlf & "The Total order is: {0:C}", SalesTotal) ' and request money for the order Console.Write("Amount Tended? ") AmountTended = Decimal.Parse(Console.ReadLine()) ' Calculate the difference owed to the customer ' or that the customer still owes to the store Difference = AmountTended - SalesTotal ShowReceipt() End Sub Private Sub ShowReceipt() Console.WriteLine() ' Display the receipt Console.WriteLine("====================================") Console.WriteLine("-/- Georgetown Cleaning Services -/-") Console.WriteLine("====================================") Console.WriteLine("Customer: {0}", Order.CustomerName) Console.WriteLine("Home Phone: {0}", Order.HomePhone) Console.WriteLine("Order Date: {0:D}", Order.OrderDate) Console.WriteLine("Order Time: {0:t}", Order.OrderTime) Console.WriteLine("------------------------------------") Console.WriteLine("Item Type Qty Unit/Price Sub-Total") Console.WriteLine("------------------------------------") Console.WriteLine("Shirts {0,3} {1,4} {2,6}", _ order.NumberOfShirts, PriceOneShirt, SubTotalShirts) Console.WriteLine("Pants {0,3} {1,4} {2,6}", _ order.NumberOfPants, PriceAPairOfPants, SubTotalPants) Console.WriteLine("Dresses {0,3} {1,4} {2,6}", _ order.NumberOfDresses, PriceOneDress, SubTotalDresses) Console.WriteLine("------------------------------------") Console.WriteLine("Total Order: {0,6}", TotalOrder.ToString("C")) Console.WriteLine("Tax Rate: {0,6}", TaxRate.ToString("P")) Console.WriteLine("Tax Amount: {0,6}", TaxAmount.ToString("C")) Console.WriteLine("Net Price: {0,6}", SalesTotal.ToString("C")) Console.WriteLine("------------------------------------") Console.WriteLine("Amount Tended: {0,6}", AmountTended.ToString("C")) Console.WriteLine("Difference: {0,6}", Difference.ToString("C")) Console.WriteLine("====================================") End Sub End Class 11. In the Solution Explorer, right-click Module1.vb and click Rename 12. Type GeorgetownDryCleaningServices.vb and press Enter. If asked whether you want to rename the file, click Yes 13. In the Solution Explorer, double-click GeorgetownDryCleaningServices.vb 14. Change the file as follows: Module GeorgetownDryCleaningServices Public Function Main() As Integer Dim Order As OrderProcessing = New OrderProcessing Order.ProcessOrder() Return 0 End Function End Module 15. Press Ctrl + F5 to execute the application. Here is an example: -/- Georgetown Cleaning Services -/Enter Customer Name: Judith Pearson Enter Customer Phone: (301) 884-0912 Enter the order date(mm/dd/yyyy): 10/05/2009 Enter the order time(hh:mm AM/PM): 08:12 Number of Shirts: 6 Number of Pants: 4 Number of Dresses: 1 The Total order is: $23.32 Amount Tended? 25 ==================================== -/- Georgetown Cleaning Services -/==================================== Customer: Judith Pearson Home Phone: (301) 884-0912 Order Date: Monday, October 05, 2009 Order Time: 8:12 AM -----------------------------------Item Type Qty Unit/Price Sub-Total
-----------------------------------Shirts 6 0.95 5.7 Pants 4 2.95 11.8 Dresses 1 4.55 4.55 -----------------------------------Total Order: $22.05 Tax Rate: 5.75 % Tax Amount: $1.27 Net Price: $23.32 -----------------------------------Amount Tended: $25.00 Difference: $1.68 ==================================== Press any key to continue . . . 16. Close the DOS window and return to your programming environment
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.
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
' 5.75%
' Request the quantity of each category of items Try Console.Write("Number of Shirts: ") order.NumberOfShirts = CInt(Console.ReadLine()) Catch Console.WriteLine("The value you typed for the number of " & _ "shirts is not a valid number") End Try Try Console.Write("Number of Pants: ") order.NumberOfPants = CInt(Console.ReadLine()) Catch Console.WriteLine("The value you typed for the number of " & _ "pair or pants is not a valid number") End Try Try Console.Write("Number of Dresses: ") order.NumberOfDresses = CInt(Console.ReadLine()) Catch Console.WriteLine("The value you typed for the number of " & _ "dresses is not a valid number") End Try ' Perform the necessary calculations SubTotalShirts = order.NumberOfShirts * PriceOneShirt SubTotalPants = order.NumberOfPants * PriceAPairOfPants SubTotalDresses = order.NumberOfDresses * PriceOneDress ' Calculate the "temporary" total of the order TotalOrder = SubTotalShirts + SubTotalPants + SubTotalDresses ' Calculate the tax amount using a constant rate TaxAmount = TotalOrder * TaxRate ' Add the tax amount to the total order SalesTotal = TotalOrder + TaxAmount ' Communicate the total to the user... Console.WriteLine(vbCrLf & "The Total order is: {0:C}", SalesTotal) ' and request money for the order Try Console.Write("Amount Tended? ") AmountTended = Decimal.Parse(Console.ReadLine()) Catch Console.WriteLine( _ "You were asked to enter an amount of money but...") End Try ' Calculate the difference owed to the customer ' or that the customer still owes to the store Difference = AmountTended - SalesTotal ShowReceipt() End Sub Private Sub ShowReceipt() Console.WriteLine() ' Display the receipt Console.WriteLine("====================================") Console.WriteLine("-/- Georgetown Cleaning Services -/-") Console.WriteLine("====================================") Console.WriteLine("Customer: {0}", Order.CustomerName) Console.WriteLine("Home Phone: {0}", Order.HomePhone) Console.WriteLine("Order Date: {0:D}", Order.OrderDate) Console.WriteLine("Order Time: {0:t}", Order.OrderTime) Console.WriteLine("------------------------------------") Console.WriteLine("Item Type Qty Unit/Price Sub-Total") Console.WriteLine("------------------------------------") Console.WriteLine("Shirts {0,3} {1,4} {2,6}", _ order.NumberOfShirts, PriceOneShirt, SubTotalShirts) Console.WriteLine("Pants {0,3} {1,4} {2,6}", _ order.NumberOfPants, PriceAPairOfPants, SubTotalPants) Console.WriteLine("Dresses {0,3} {1,4} {2,6}", _ order.NumberOfDresses, PriceOneDress, SubTotalDresses) Console.WriteLine("------------------------------------") Console.WriteLine("Total Order: {0,6}", TotalOrder.ToString("C")) Console.WriteLine("Tax Rate: {0,6}", TaxRate.ToString("P")) Console.WriteLine("Tax Amount: {0,6}", TaxAmount.ToString("C")) Console.WriteLine("Net Price: {0,6}", SalesTotal.ToString("C")) Console.WriteLine("------------------------------------") Console.WriteLine("Amount Tended: {0,6}", AmountTended.ToString("C")) Console.WriteLine("Difference: {0,6}", Difference.ToString("C")) Console.WriteLine("====================================") End Sub End Class 11. In the Solution Explorer, right-click Module1.vb and click Rename 12. Type GeorgetownDryCleaningServices.vb and press Enter. If asked whether you want to rename the file, click Yes 13. In the Solution Explorer, double-click GeorgetownDryCleaningServices.vb 14. Change the file as follows: Module GeorgetownDryCleaningServices Public Function Main() As Integer Dim Order As OrderProcessing = New OrderProcessing
Order.ProcessOrder() Return 0 End Function End Module 15. Press Ctrl + F5 to execute the application. Here is an example: -/- Georgetown Cleaning Services -/Enter Customer Name: Judith Pearson Enter Customer Phone: (301) 884-0912 Enter the order date(mm/dd/yyyy): 10/05/2009 Enter the order time(hh:mm AM/PM): 08:12 Number of Shirts: 6 Number of Pants: 4 Number of Dresses: 1 The Total order is: $23.32 Amount Tended? 25 ==================================== -/- Georgetown Cleaning Services -/==================================== Customer: Judith Pearson Home Phone: (301) 884-0912 Order Date: Monday, October 05, 2009 Order Time: 8:12 AM -----------------------------------Item Type Qty Unit/Price Sub-Total -----------------------------------Shirts 6 0.95 5.7 Pants 4 2.95 11.8 Dresses 1 4.55 4.55 -----------------------------------Total Order: $22.05 Tax Rate: 5.75 % Tax Amount: $1.27 Net Price: $23.32 -----------------------------------Amount Tended: $25.00 Difference: $1.68 ==================================== Press any key to continue . . . 16. Close the DOS window and return to your programming environment
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
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
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.
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
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
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.
' 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
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
1.
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.
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
Home
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
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
Flavors.Add("Caramel Au Lait") Flavors.Add("Chunky Butter") Flavors.Add("Chocolate Cookie") Ingredients = New Collection Ingredients.Add("No Ingredient") Ingredients.Add("Peanuts") Ingredients.Add("M & M") Ingredients.Add("Cookies") Containers = New Collection Containers.Add("Cone") Containers.Add("Cup") Containers.Add("Bowl") End Sub ' This method requests a flavor from the user and returns the choice Public Sub ChooseFlavor() ' Make sure the user selects a valid number that represents a flavor... Do ' In case the user types a symbol that is not a number Try Console.WriteLine("What type of flavor do you want?") For i As Integer = 1 To Flavors.Count Step 1 Console.WriteLine("{0} {1}", i, Flavors(i)) Next Console.Write("Your Choice? ") ChoiceFlavor = CInt(Console.ReadLine()) Catch ex As InvalidCastException ' display an appropriate message Console.WriteLine("You must enter a valid " & _ "number and no other character!") End Try ' If the user typed an invalid number out of the allowed range ' let him or her know and provide another chance If ChoiceFlavor < 1 Or ChoiceFlavor > Flavors.Count Then Console.WriteLine("Invalid Choice - Try Again!" & vbCrLf) End If Loop While ChoiceFlavor < 1 Or ChoiceFlavor > Flavors.Count End Sub ' This method allows the user to select a container Public Sub ChooseContainer() ' Make sure the user selects a valid number that represents a container Do ' If the user types a symbol that is not a number Try Console.WriteLine("What type of container do you want?") For i As Integer = 1 To Containers.Count Step 1 Console.WriteLine("{0} {1}", i, Containers(i)) Next Console.Write("Your Choice? ") ChoiceContainer = CInt(Console.ReadLine()) Catch ex As InvalidCastException Console.WriteLine("You must enter a valid " & _ "number and no other character!") End Try ' If the user typed an invalid number out of the allowed range ' let him or her know and provide another chance If ChoiceContainer < 1 Or ChoiceContainer > Containers.Count Then Console.WriteLine("Invalid Choice - Try Again!") End If Loop While ChoiceContainer < 1 Or ChoiceContainer > Containers.Count End Sub Public Sub ChooseIngredient() Do Try Console.WriteLine("Do you want an ingredient or not") For i As Integer = 1 To
Ingredients.Count Step 1 Console.WriteLine("{0} {1}", i, Ingredients(i)) Next Console.Write("Your Choice? ") ChoiceIngredient = CInt(Console.ReadLine()) Catch ex As InvalidCastException Console.WriteLine("You must enter a valid " & _ "number and no other character!") End Try If ChoiceIngredient < 1 Or ChoiceIngredient > Ingredients.Count Then Console.WriteLine("Invalid Choice - Try Again!") End If Loop While ChoiceIngredient < 1 Or ChoiceIngredient > Ingredients.Count End Sub Public Sub SpecifyNumberOfScoops() Do Try Console.Write("How many scoops(1, 2, or 3)? ") Scoops = CInt(Console.ReadLine()) Catch ex As InvalidCastException Console.WriteLine("You must enter a valid " & _ "number and no other character!") End Try If Scoops < 1 Or Scoops > 3 Then Console.WriteLine("Invalid Choice - Try Again!") End If Loop While Scoops < 1 Or Scoops > 3 End Sub ' This method is used to process a customer order ' It uses the values of the above methods Public Sub ProcessAnOrder() Dim PriceIngredient As Double Dim PriceScoop As Double ' Let the user know that this is a vending machine Console.WriteLine("Ice Cream Vending Machine") ' Let the user select the components of the ice cream ChooseFlavor() ChooseContainer() ChooseIngredient() SpecifyNumberOfScoops() ' If the user selects an ingredient instead of "No Ingredient", ' add $0.50 to the order If ChoiceIngredient = 2 Or _ ChoiceIngredient = 3 Or _ ChoiceIngredient = 4 Then PriceIngredient = 0.5 Else PriceIngredient = 0.0 End If ' Instead of multiplying a number scoops to a value, ' We will use an incremental value depending on the number of scoops If Scoops = 1 Then PriceScoop = 0.65 ElseIf Scoops = 2 Then PriceScoop = 1.05 Else PriceScoop = 1.55 End If ' Calculate the total price of the ice cream TotalPrice = BasePrice + PriceScoop + PriceIngredient ' Create the ice cream... ' And display a receipt to the user DisplayReceipt() End Sub ' This method is used to display a receipt to the user Public Sub DisplayReceipt() Console.WriteLine(vbCrLf & "Ice Cream
Order") Console.WriteLine("Flavor: Flavors(ChoiceFlavor)) Console.WriteLine("Container: Containers(ChoiceContainer)) Console.WriteLine("Ingredient: Ingredients(ChoiceIngredient)) Console.WriteLine("Scoops: Scoops) Console.WriteLine("Total Price: & vbCrLf, TotalPrice) End Sub Public Sub Save() Dim NameOfFile As String Console.WriteLine("Please enter your initials or the name " & _ "we will use to remember your order: ") NameOfFile = Console.ReadLine() NameOfFile = NameOfFile & ".icr" ' Find out if the user entered a name of a ' file that is already in the machine If File.Exists(NameOfFile) Then Dim Answer As String Dim stmIceCream As FileStream = _ New FileStream(NameOfFile, FileMode.Create) Dim bnwIceCream As BinaryWriter = New BinaryWriter(stmIceCream) ' If so, find out if the user wants to replace the old file Console.WriteLine("The file you entered exists already.") Console.Write("Do you want to replace it(y/n)?") Answer = Console.ReadLine() ' If the customer wants to replace it... If Answer = "y" Or Answer = "Y" Then ' ... do so Console.WriteLine("The former order with the " & _ "same name will be replaced") Console.WriteLine(vbCrLf & "=-= Ice Cream Vending Machine =-=") Console.WriteLine(" Saving Order: {0}", NameOfFile) bnwIceCream.Write(Flavors(ChoiceFlavor)) bnwIceCream.Write(Containers(ChoiceContainer)) bnwIceCream.Write(Ingredients(ChoiceIngredient)) bnwIceCream.Write(Scoops) bnwIceCream.Write(TotalPrice) ' If the customer wants to save the ' new order with a different name ElseIf Answer = "n" Or Answer = "N" Then ' Ask the user to enter a name to remember the order Console.Write("Please enter a name we will " & _ "use to remember this order: ") NameOfFile = Console.ReadLine() NameOfFile = NameOfFile & ".icr" stmIceCream = New FileStream(NameOfFile, FileMode.Create) bnwIceCream = New BinaryWriter(stmIceCream) Console.WriteLine(vbCrLf & "=-= Ice Cream Vending Machine =-=") Console.WriteLine(" Saving Order: {0}", NameOfFile) bnwIceCream.Write(Flavors(ChoiceFlavor)) bnwIceCream.Write(Containers(ChoiceContainer)) bnwIceCream.Write(Ingredients(ChoiceIngredient)) bnwIceCream.Write(Scoops) bnwIceCream.Write(TotalPrice) Else {0}", {0}", {0}", {0}", {0:C}"
Console.WriteLine("Invalid Answer - We will close") bnwIceCream.Close() stmIceCream.Close() End If Else Dim stmIceCream As FileStream = _ New FileStream(NameOfFile, FileMode.Create) Dim bnwIceCream As BinaryWriter = New BinaryWriter(stmIceCream) Console.WriteLine(vbCrLf & "=-= Ice Cream Vending Machine =-=") Console.WriteLine(" Saving Order: {0}", NameOfFile) bnwIceCream.Write(Flavors(ChoiceFlavor)) bnwIceCream.Write(Containers(ChoiceContainer)) bnwIceCream.Write(Ingredients(ChoiceIngredient)) bnwIceCream.Write(Scoops) bnwIceCream.Write(TotalPrice) bnwIceCream.Close() stmIceCream.Close() End If End Sub Public Sub Open() Dim NameOfFile As String Dim SelectedFlavor As String Dim SelectedContainer As String Dim SelectedIngredient As String ' Ask the user to enter a name of a previously saved order Console.Write("Please enter the name you previously " & _ "gave to remember your order: ") NameOfFile = Console.ReadLine() NameOfFile = NameOfFile & ".icr" Dim stmIceCream As FileStream = New FileStream(NameOfFile, FileMode.Open) Dim bnrIceCream As BinaryReader = New BinaryReader(stmIceCream) ' Find out if this order was previously saved in the machine If File.Exists(NameOfFile) Then ' If so, open it SelectedFlavor = bnrIceCream.ReadString() SelectedContainer = bnrIceCream.ReadString() SelectedIngredient = bnrIceCream.ReadString() Scoops = bnrIceCream.ReadInt32() TotalPrice = bnrIceCream.ReadDouble() ' And display it to the user Console.WriteLine(vbCrLf & "=-= Ice Cream Vending Machine =-=") Console.WriteLine(" Previous Order: {0}", NameOfFile) Console.WriteLine("Flavor: {0}", SelectedFlavor) Console.WriteLine("Container: {0}", SelectedContainer) Console.WriteLine("Ingredient: {0}", SelectedIngredient) Console.WriteLine("Scoops: {0}", Scoops) Console.WriteLine("Total Price: {0:C}" & vbCrLf, TotalPrice) bnrIceCream.Close() stmIceCream.Close() Else Console.WriteLine("The name you entered is not " & _ "registered in our previous orders") End If End Sub End Class Source File: Exercise.vb Imports System Public Class Exercise Public Shared Sub main() Dim IC As IceCream = New IceCream Dim Answer As String = "n"
Console.Write("Have you ordered here before(y/n)? ") Answer = Console.ReadLine() If Answer = "y" Or Answer = "Y" Then IC.Open() Else IC.ProcessAnOrder() Console.Write("Do you want us to remember this order the next " & _ "time you come to get your ice cream (y/n)? ") Answer = Console.ReadLine() If Answer = "y" Or Answer = "Y" Then IC.Save() End If End If End Sub End Class 2. Save the file and switch to the Command Prompt 3. To compile it, type vbc /out:"Ice Cream Vending Machine".exe IceCream.vb Exercise.vb and press Enter 4. To execute it, type "Ice Cream Vending Machine" and press Enter. Here is an example: Have you ordered here before(y/n)? y Please enter the name you previously gave to remember your order: Jane44 =-= Ice Cream Vending Machine =-= Previous Order: Jane44.icr Flavor: Chocolate Brownies Container: Cone Ingredient: Cookies Scoops: 2 Total Price: $3.10 5. Return to the IceCream.vb file
Previous
Next
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.
Previous
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
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:
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.
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.
Previous
Home