0% found this document useful (0 votes)
15 views

unit2chapter2VB

Jsjsjssk

Uploaded by

akshayamith887
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

unit2chapter2VB

Jsjsjssk

Uploaded by

akshayamith887
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

1. Essential Visual Basic .

NET
1.1 Introduction : Visual Basic .NET (VB.NET) is an object-oriented computer programming language
implemented on the .NET Framework. Although it is an evolution of classic Visual Basic language, it is not
backwards-compatible with VB6, and any code written in the old version does not compile under VB.NET.
Like all other .NET languages, VB.NET has complete support for object-oriented concepts. Everything in
VB.NET is an object, including all of the primitive types (Short, Integer, Long, String, Boolean, etc.) and user-
defined types, events, and even assemblies. All objects inherits from the base class Object. VB.NET is
implemented by Microsoft's .NET framework. Therefore, it has full access to all the libraries in the .Net
Framework. The following reasons make VB.Net a widely used professional language:
• Modern, general purpose.
• Object oriented.
• Component oriented.
• Easy to learn.
• Structured language.
• It produces efficient programs.
• It can be compiled on a variety of computer platforms.
• Part of .Net Framework.

1.2 Features of VB.Net :


• Boolean Conditions
• Automatic Garbage Collection
• Standard Library
• Assembly Versioning
• Properties and Events
• Delegates and Events Management
• Easy-to-use Generics
• Indexers
• Conditional Compilation
• Simple Multithreading

1.3 The .Net Framework and the Common Language Runtime:


The .Net framework is a revolutionary platform that helps you to write the following types of applications:
• Windows applications
• Web applications
• Web services
The .Net framework applications are multi-platform applications. The framework has been designed in such a
way that it can be used from any of the following languages: Visual Basic, C#, C++, Jscript, and COBOL, etc.
All these languages can access the framework as well as communicate with each other.
The .Net framework consists of an enormous library of codes used by the client languages like VB.Net. These
languages use object-oriented methodology.

Following are some of the components of the .Net framework:


• Common Language Runtime (CLR)
• The .Net Framework Class Library
• Common Language Specification
• Common Type System
• Metadata and Assemblies
• Windows Forms
• ASP.Net and ASP.Net AJAX
• ADO.Net
• Windows Workflow Foundation (WF)
• Windows Presentation Foundation
• Windows Communication Foundation (WCF)
• LINQ

Common Language Runtime (CLR) : The CLR is the module that actually runs your VB .NET
applications. When you create a VB .NET application, what really happens is that your code is compiled into
the CLR's Intermediate Language (named MSIL, or IL for short), much like bytecodes in Java. When you run
the application, that IL code is translated into the binary code your computer can understand by some special
compilers built into the CLR. Compilers translate your code into something that your machine's hardware, or
other software, can deal with directly. In this way, Microsoft can one day create a CLR for operating systems
other than Windows, and your VB .NET applications, compiled into IL, will run on them.

1.4 The System Namespaces :


The System namespace contains fundamental classes and base classes that define commonly-used value and
reference data types, events and event handlers, interfaces, attributes, and processing exceptions.

• System-Includes essential classes and base classes that define commonlyused data types, events and
event handlers, interfaces, attributes, exceptions, and so on.
• System.Collections-Includes interfaces and classes that define various collections of objects, including
such collections as lists, queues, arrays, hash tables, and dictionaries.
• System.Data-Includes classes that make up ADO.NET. ADO.NET lets you build data-handling
components that manage data from multiple distributed data sources.
• System.Data.OleDb-Includes classes that support the OLE DB .NET data provider.
• System.Data.SqlClient-Includes classes that support the SQL Server .NET data provider.
• System.Diagnostics-Includes classes that allow you to debug your application and to step through your
code. Also includes code to start system processes, read and write to event logs, and monitor system
performance.
• System.Drawing-Provides access to the GDI+ graphics packages that give you access to drawing
methods.
• System.Drawing.Drawing2D-Includes classes that support advanced two-dimensional and vector
graphics.
• System.Drawing.Imaging-Includes classes that support advanced GDI+ imaging.
• System.Drawing.Printing-Includes classes that allow you to customize and perform printing.
• System.Drawing.Text-Includes classes that support advanced GDI+ typography operations. The classes
in this namespace allow users to create and use collections of fonts.
• System.Globalization-Includes classes that specify culture-related information, including the language,
the country/region, calendars, the format patterns for dates, currency and numbers, the sort order for
strings, and so on.
• System.IO-Includes types that support synchronous and asynchronous reading from and writing to both
data streams and files.
• System.Net-Provides an interface to many of the protocols used on the Internet.
• System.Net.Sockets-Includes classes that support the Windows Sockets interface. If you've worked with
the Winsock API, you should be able to develop applications using the Socket class.
• System.Reflection-Includes classes and interfaces that return information about types, methods, and
fields, and also have the ability to dynamically create and invoke types.
• System.Security-Includes classes that support the structure of the common language runtime security
system.
• System.Threading-Includes classes and interfaces that enable multithreaded programming.
• System.Web-Includes classes and interfaces that support browser/server communication. Included in this
namespace are the HTTPRequest class that provides information about HTTP requests, the
HTTPResponse class that manages HTTP output to the client, and the HTTPServerUtility class that
provides access to server-side utilities and processes. You can also use cookies, support file transfer, and
more with these classes.
• System.Web.Security-Includes classes that are used to implement ASP.NET security in Web server
applications.
• System.Web.Services-Includes classes that let you build and use Web services, programmable entities
on Web Server that code can communicate with using standard Internet protocols.
• System.Windows.Forms-Includes classes for creating Windows-based forms that make use of the user
interface controls and other features available in the Windows operating system.
• System.Xml-Includes classes that support processing of XML.

1.5 Creating Console Application :


A console program has no graphics. It is text. Easy to develop, it uses few resources and is efficient. These
programs, however, will readily accomplish an analytical or processing task.
To create a console application in Visual Studio
• On the File menu in Microsoft Visual Studio, point to New and then click Project.
• In the New Project dialog box, select a language in the Installed Templates box, and then select
the Console Application template.
• Type a name for the application in the Name box, and in the Location box, type the path to where you
want the application to be created, and then click OK.

Module Module1
Sub Main()
System.Console.WriteLine("Hello world")
End Sub
End Module

When the above code is compiled and executed, it produces the following result:
Hello world

Let us look various parts of the above program:


• Module declaration, the module Module1. VB.Net is completely object oriented, so every program
must contain a module of a class that contains the data and procedures that your program uses.
• Classes or Modules generally would contain more than one procedure. Procedures contain the
executable code, or in other words, they define the behavior of the class. A procedure could be any of
the following:
o Function
o Sub
o Operator
o Get
o Set
o AddHandler
o RemoveHandler
o RaiseEvent
• The next line defines the Main procedure, which is the entry point for all VB.Net programs. The Main
procedure states what the module or class will do when executed.
• The Main procedure specifies its behavior with the statement
System.Console.WriteLine("Hello World")
WriteLine is a method of the Console class defined in the Systemnamespace. This statement causes the
message "Hello, World!" to be displayed on the screen.

1.6 Building VB .NET applications :


VB.Net programmers have made extensive use of forms to build user interfaces. Each time you create a
Windows application, Visual Studio will display a default blank form, onto which you can drag and drop
controls from the Visual Studio Toolbox window.
1. The first step is to start a new project and build a form. Open your Visual Studio and select File -
>NewProject and select Visual Basic from the New project dialog box and select Windows Froms
Application. Enter your project name instead of WindowsApplication1 in the bottom of dialouge box
and click OK button.
2. Select project type from New project dialog Box i.e. Windows Forms Applications.
3. When you add a Windows Form to your project, many of the forms properties are set by default. At the
top of the form there is a title bar which displays the forms title. Form1 is the default name, you can
change the name to your convenience . The title bar also includes the control box, which holds the
minimize, maximize, and close buttons.
4. To set any properties of the Form, you can use Visual Studio Property window to change it. For example
, to change the forms title from Form1 to MyForm, click on Form1 and move to the right side down
Properties window, set Text property to MyForm.
5. You can also set the properties of the Form1 through coding. For coding, you should right-click the
design surface or code window and then clicking View Code. When you right click on Form then you
will get code behind window, there you can write your code.

1.7 Integrated Development Environment (IDE) For VB.Net :


An integrated development environment (IDE), also known as integrated design environment and integrated
debugging environment, is a type of computer software that assists computer programmers to develop
software. Microsoft provides the following development tools for VB.Net programming:
• Visual Studio 2010 (VS)
• Visual Basic 2010 Express (VBE)
• Visual Web Developer
Using these tools, you can write all kinds of VB.Net programs from simple command-line applications to more
complex applications.
Visual Studio IDE is extremely customizable which means that you can move, hide, or modify the menus,
toolbars, and windows. You can create your own toolbars and then dock, undock, or rearrange them. Finally
you can change the behavior of the built-in text editors.

The IDE was designed as a Single Document Interface (SDI). In a Single Document Interface, each window is
a free-floating window that is contained within a main window and can move anywhere on the screen as long
as Visual Basic is the current application. But, in Visual Basic 6.0, the IDE is in a Multiple Document Interface
(MDI) format. In this format, the windows associated with the project will stay within a single container known
as the parent. Code and form-based windows will stay within the main container form.

• The Visual Basic startup dialog box:

• Menu System : This Menu System displays the commands that are required to build an application. The
main menu items have sub menu items that can be chosen when needed. The toolbars in the menu bar
provide quick access to the commonly used commands and a button in the toolbar is clicked once to carry
out the action represented by it.
• Toolbars : The Toolbars contains a set of controls that are used to place on a Form at design time thereby
creating the user interface area. Additional controls can be included in the toolbox by using the Components
menu item on the Project menu.

Control Description

Pointer Provides a way to move and resize the controls form

Displays icons/bitmaps and metafiles. It displays text or acts as a visual


PictureBox
container for other controls.

TextBox Used to display message and enter text.

Frame Serves as a visual and functional container for controls

CommandButton Used to carry out the specified action when the user chooses it.

CheckBox Displays a True/False or Yes/No option.

OptionButton control which is a part of an option group allows the user to


OptionButton
select only one option even it displays mulitiple choices.
ListBox Displays a list of items from which a user can select one.

Contains a TextBox and a ListBox. This allows the user to select an ietm from
ComboBox
the dropdown ListBox, or to type in a selection in the TextBox.
HScrollBar and These controls allow the user to select a value within the specified range of
VScrollBar values
Timer Executes the timer events at specified intervals of time

DriveListBox Displays the valid disk drives and allows the user to select one of them.

DirListBox Allows the user to select the directories and paths, which are displayed.

FileListBox Displays a set of files from which a user can select the desired one.

Shape Used to add shape (rectangle, square or circle) to a Form

Line Used to draw straight line to the Form

used to display images such as icons, bitmaps and metafiles. But less
Image
capability than the PictureBox
Enables the use to connect to an existing database and display information
Data
from it.
Used to link or embed an object, display and manipulate data from other
OLE
windows based applications.

Label Displays a text that the user cannot modify or interact with.

• Project Explorer : Docked on the right side of the screen, just under the tollbar, is the Project
Explorer window. The Project Explorer as shown in in figure servres as a quick reference to the various
elements of a project namely form, classes and modules. All of the object that make up the application
are packed in a project. A simple project will typically contain one form, which is a window that is
designed as part of a program's interface. It is possible to develop any number of forms for use in a
program, although a program may consist of a single form. In addition to forms, the Project Explorer
window also lists code modules and classes.
• Object Browser : The Object Browser allows us to browse through the various properties, events
and methods that are made available to us. It is accessed by selecting Object Browser from the View
menu or pressing the key F2. The left column of the Object Browser lists the objects and classes that are
available in the projects that are opened and the controls that have been referenced in them. It is possible
for us to scroll through the list and select the object or class that we wish to inspect. After an object is
picked up from the Classes list, we can see its members (properties, methods and events) in the right
column.
• Graphical Designers : When you're working on a project that has user interface elements-such as
forms, VB .NET can display what those elements will look like at run time. There are several different
types of graphical designers, including: Windows form designers, Web form designers, Component
designers , XML designers.
• Code Designers : Unlike graphical designers, code designers let you edit the code for a component.
You can use the tabs at the top center of the IDE to switch between graphical designers (such as the tabs
Form1.vb[Design], which displays a graphical designer, and the Form1.vb tab, which displays the
corresponding code designer). You can also switch between graphical and code designers using the
Designer and Code items in the View menu, or you can use the top two buttons at left in the Solution
Explorer.
• IntelliSense : One useful feature of VB .NET code designers is Microsoft's IntelliSense. IntelliSense
is what's responsible for those boxes that open as you write your code, listing all the possible options
and even completing your typing for you. IntelliSense is one of the first things you encounter when you
use VB .NET. IntelliSense is made up of a number of options, including: List Members-Lists the
members of an object. Parameter Info-Lists the arguments of procedure calls. Quick Info-Displays
information in tool tips as the mouse rests on elements in your code. Word-Completes typed words.
Automatic Brace Matching-Adds parentheses or braces as needed.
• Solution Explorer : This window gives you an overview of the solution you're working with,
including all the projects in it, and the items in those projects. This tool displays a hierarchy-with the
solution at the top of the hierarchy, the projects one step down in the hierarchy, and the items in each
project as the next step down. You can set the properties of various items in a project by selecting them
in the Solution Explorer and then setting their properties in the properties window. And you can set
properties of solutions and projects by right-clicking them and selecting the Properties item in the menu
that appears, or you can select an item and click the properties button, which is the right-most button at
the top of the Solutions Explorer.
• Class View Window : This view presents solutions and projects in terms of the classes they
contain, and the members of these classes. Using the Class View window gives you an easy way of
jumping to a member of class that you want to access quickly-just find it in the Class View window,
and double-click it to bring it up in a code designer.
• Properties Window : The Properties window is divided into two columns of text, with the
properties on the left, and their settings on the right. The object you're setting properties for appears in
the drop-down list box at the top of the Properties window, and you can select from all the available
objects using that list box. When you select a property, Visual Basic will give you an explanation of the
property in the panel at the bottom of the Properties window. And you can display the properties
alphabetically by clicking the second button from the left at the top of the Properties window, or in
categories by clicking the left-most button.
• Dynamic Help Window : The window that shares the Properties window's space, however, is quite
new-the Dynamic Help window. Visual Basic .NET includes the usual Help menu with Contents, Index,
and Search items, of course, but it also now supports dynamic help, which looks things up for you
automatically. You can see the Dynamic Help window by clicking the Dynamic Help tab under the
Properties window.
• Server Explorer : You use the Server Explorer, to explore what's going on in a server, and it's a
great tool to help make distant severs feel less distant, because you can see everything you need in an
easy graphical environment. You can do more than just look using the Server Explorer too-you can drag
and drop whole items onto Windows forms or Web forms from the Server Explorer.
• Output Window : If you look at the bottom of the IDE, you'll see two tabs for the Output and
Breakpoints windows. We'll look at the Breakpoints window when we discuss debugging, because it
lets you manage the breakpoints at which program execution halts when you're debugging your code.
The Output window, gives you the results of building and running programs.
• Command Window : This window is a little like the Immediate window in VB6, because you can
enter commands like File.AddNewProject here and VB .NET will display the Add New Project dialog
box. However, this window is not exactly like the Immediate window, because you can't enter Visual
Basic code and have it executed.And there are other windows that we'll see as needed, such as when
we're discussing debugging programs where we'll introduce the Call Stack window, the Breakpoints
window, Watch and Value display windows, Autos and Locals windows, and so on.
2. The Visual Basic Language
2.1 The Visual Basic Keywords : Keywords are reserved, which means that you cannot use them
as names for programming elements such as variables or procedures and you use them to build your programs.
For example , Loop , Next , Private , ReadOnly etc

2.2 Visual Basic Statements: A Visual Basic statement is a complete instruction. It can contain:
• keywords—Words reserved for Visual Basic's use.
• operators—Symbols used to perform operations, like +, which performs addition operations; -, which
performs subtraction operations; and so on.
• variables—Symbolic names given to values stored in memory and declared with the Dim keyword. For
example, if you've declared a variable named temperature as an Integer type, you can store integer
values like 72 or 83 in it.
• literal values—Simple values, like 5 or "Hello."
• constants—The same as variables, except that constants are assigned a value that cannot then be altered.
• expressions—Combinations of terms and/or keywords that yield a value. For example, if the variable
temperature holds the value 72, then the expression temperature + 3 yields the value 75

Each statement is one of the following:


• A declaration statement, which can name and create a variable, constant, or procedure and can also
specify a data type. The data type can be Boolean, Byte, Char, Date, Decimal, Double, Integer, Long,
Object, Short, Single, or String; or the name of an enumeration (a series of constants defined at the
same time), structure, class, or interface.
• An executable statement, which can perform an action. These statements can execute a method or
function, or they can loop through code using one of the Visual Basic loops we'll see in this chapter,
which execute a series of statements repetitively, or they can be an assignment statement, which assign a
value or expression to a variable or constant such as this: temperature = 72, and so on.

2.3 Statement Syntax: Each statement has its own syntax.


[ <attrlist> ] [{ Public | Protected | Friend | Protected Friend |
Private | Static }] [ Shared ] [ Shadows ] [ ReadOnly ] Dim [ WithEvents ]
name[ (boundlist) ] [ As [ New ] type ] [ = initexpr ]

• attrlist-A list of attributes that apply to the variables you're declaring in this statement. You separate
multiple attributes with commas.
• Public-Gives variables public access, which means there are no restrictions on their accessibility. You
can use Public only at module, namespace, or file level (which means you can't use it inside a
procedure). Note that if you specify Public, you can omit the Dim keyword if you want to.
• Protected-Gives variables protected access, which means they are accessible only from within their own
class or from a class derived from that class. You can use Protected only at class level (which means
you can't use it inside a procedure), because you use it to declare members of a class. Note that if you
specify Protected, you can omit the Dim keyword if you want to.
• Friend-Gives variables friend access, which means they are accessible from within the program that
contains their declaration, as well as anywhere else in the same assembly. You can use Friend only at
module, namespace, or file level (which means you can't use it inside a procedure). Note that if you
specify Friend, you can omit the Dim keyword if you want to.
• Protected Friend-Gives variables both protected and friend access, which means they can be used by
code in the same assembly, as well as by code in derived classes.
• Private-Gives variables private access, which means they are accessible only from within their
declaration context (usually a class), including any nested procedures. You can use Private only at
module, namespace, or file level (which means you can't use it inside a procedure). Note that if you
specify Private, you can omit the Dim keyword if you want to.
• Static-Makes variables static, which means they'll retain their values, even after the procedure in which
they're declared ends. You can declare static variables inside a procedure or a block within a procedure,
but not at class or module level. Note that if you specify Static, you can omit the Dim keyword if you
want to, but you cannot use either Shadows or Shared.
• Shared-Declares a shared variable, which means it is not associated with a specific instance of a class or
structure, but can be shared across many instances. You access a shared variable by referring to it either
with its class or structure name, or with the variable name of an instance of the class or structure. You
can use Shared only at module, namespace, or file level (but not at the procedure level). Note that if you
specify Shared, you can omit the Dim keyword if you want to.
• Shadows-Makes this variable a shadow of an identically named programming element in a base class. A
shadowed element is unavailable in the derived class that shadows it. You can use Shadows only at
module, namespace, or file level (but not inside a procedure). This means you can declare shadowing
variables in a source file or inside a module, class, or structure, but not inside a procedure. Note that if
you specify Shadows, you can omit the Dim keyword if you want to.
• ReadOnly-Means this variable only can be read and not written. This can be useful for creating constant
members of reference types, such as an object variable with preset data members. You can use
ReadOnly only at module, namespace, or file level (but not inside procedures). Note that if you specify
ReadOnly, you can omit the Dim keyword if you want to.
• WithEvents-Specifies that this variable is used to respond to events caused by the instance that was
assigned to the variable. Note that you cannot specify both WithEvents and New in the same variable
declaration.
• name-The name of the variable. You separate multiple variables by commas. If you specify multiple
variables, each variable is declared of the data type given in the first As clause encountered after its
name part.
• boundlist-Used to declare arrays; gives the upper bounds of the dimensions of an array variable.
Multiple upper bounds are separated by commas. An array can have up to 60 dimensions.
• New-Means you want to create a new object immediately. If you use New when declaring an object
variable, a new instance of the object is created. Note that you cannot use both WithEvents and New in
the same declaration.
• type-The data type of the variable. Can be Boolean, Byte, Char, Date, Decimal, Double, Integer,
Long, Object, Short, Single, or String; or the name of an enumeration, structure, class, or interface. To
specify the type, you use a separate As clause for each variable, or you can declare a number of
variables of the same type by using common As clauses. If you do not specify type, the variable takes
the data type of initexpr. Note that if you don't specify either type or initexpr, the data type is set to
Object.
• initexpr-An initialization expression that is evaluated and the result is assigned to the variable when it is
created. Note that if you declare more than one variable with the same As clause, you cannot supply
initexpr for those variables.

2.4 Overview :
• block - a block of statements is made up of a number of statements, enclosed inside another statement
designed for that purpose.
• File - Refers to code in the same file.
• Variable - A named memory location of a specific data type (such as Integer) that stores data. You can
assign data to a variable with the assignment operator; for example, if you have a variable named
temperature, you can assign it a value of 72 like this: temperature = 72.
• Procedure - A callable series of statements that may or may not return a value. You may pass data to the
procedure in the form of parameters in a procedure call like this addem(2, 3), where 2 and 3 are
parameters I'm passing to a procedure named addem. When the series of statements terminates, control
returns to the statement that called the procedure.
• sub procedure - A procedure that does not return a value.
• Function - A procedure that returns a value.
• Method - A procedure that is built into a class.
• Constructor - A special method that is automatically called when you create an object from a class. Used
to initialize and customize the object. You can pass data to constructor methods just like other methods.
• Module - Visual Basic modules are designed to hold code-that is, to separate the code in them from
other, possibly conflicting, code. Their main purpose is to make your code more modular, and if your
program is a long one, you should consider breaking it up into modules.
• Class - This is an OOP class, which can contain both code and data; you use classes to create objects. A
class can have members, which are elements that can be accessible from outside the class if you so
specify. Data members are called fields, procedure members are called methods.
• Object - This is an instance of a class, much like a variable is an instance of a data type.
• shared or static members and instance members - Fields and methods that apply to a class and are
invoked with the class name are called shared or static fields and methods; the fields and methods that
apply to objects created from the class are called instance fields and methods.
• Structure - Also an OOP element, just like a class but with some additional restrictions. In VB6 and
earlier, you used structures to create user-defined types; now they are another form of OOP classes.
2.5 Understanding Attributes :
Attributes are items that let you specify information about the items you're using in VB .NET. You enclose
attributes in angle brackets, < and >, and you use them when VB .NET needs to know more than standard
syntax can specify. For example, if you want to call one of the functions that make up the Windows Application
Programming Interface (API), you have to specify the Windows Dynamic Link Libraries (DLLs) that the
function you're calling resides in, which you can do with the DllImport attribute, like this:
Public Shared Function <DllImport("user32.dll")> MessageBox(ByVal Hwnd…

2.6 The Option and Imports Statements :


The Option statement sets a number of options for the rest of your code.

• Option Explicit— Set to On or Off. On is the default. Requires declaration of all variables before they
are used (this is the default).
• Option Compare— Set to Binary or Text. This specifies if strings are compared using binary or text
comparison operations.
• Option Strict— Set to On or Off. Off is the default. When you assign a value of one type to a variable
of another type Visual Basic will consider that an error if this option is on and there is any possibility of
data loss,

The Imports statement imports namespaces into your code, making them more readily available.You use
Imports statements to import a namespace so you don't have to qualify items in that namespace by listing the
entire namespace when you refer to them.

2.7 Declaring Constants : In VB.Net, constants are declared using the Const statement. The Const
statement is used at module, class, structure, procedure, or block level for use in place of literal values. The
syntax for the Const statement is:

[ <attrlist> ] [{ Public | Protected | Friend | Protected Friend |


Private }] [ Shadows ] Const name [ As type ] = initexpr

Each attribute in the attrlist list must use this syntax:


<attrname [({ attrargs | attrinit })]>

Here are the parts of the attrlist list:


• attrname-Name of the attribute.
• attrargs-List of arguments for this attribute. Separate multiple arguments with commas.
• attrinit-List of field or property initializers for this attribute. Separate multiple arguments with commas.
Example:
Imports System.Console
Module Module1
Sub Main()
Const Pi = 3.14159
Dim Radius, Area As Single
Radius = 1
Area = Pi * Radius * Radius
WriteLine("Area = " & Str(Area))
End Sub

End Module

2.8 Creating Enumerations: An enumerated type is declared using the Enum statement. The Enum
statement declares an enumeration and defines the values of its members. The Enum statement can be used at
the module, class, structure, procedure, or block level. The syntax for the Enum statement is as follows:

[ <attrlist> ] [{ Public | Protected | Friend | Protected Friend |


Private }] [ Shadows ] Enum name [ As type ]
[<attrlist1 >] membname1 [ = initexpr1 ]
[<attrlist2 >] membname2 [ = initexpr2 ]

[<attrlistn>] membnamen [ = initexprn ]
End Enum
Example:
Module Module1
Enum Days
Sunday = 1
Monday = 2
Tuesday = 3
Wednesday = 4
Thursday = 5
Friday = 6
Saturday = 7
End Enum
Sub Main()
System.Console.WriteLine("Friday is day " & Days.Friday)
End Sub
End Module

2.9 Declaring Variables : The Dim statement is used for variable declaration and storage allocation
for one or more variables. The Dim statement is used at module, class, structure, procedure or block level.
Syntax for variable declaration in VB.Net is:

[ <attrlist> ] [{ Public | Protected | Friend | Protected Friend |


Private | Static }] [ Shared ] [ Shadows ] [ ReadOnly ] Dim [ WithEvents ]
name[ (boundlist) ] [ As [ New ] type ] [ = initexpr ]

Each attribute in the attrlist list must use this syntax:

<attrname [({ attrargs | attrinit })]>

Example :
Dim EmployeeID As Integer = 1
Dim EmployeeName As String = "Bob Owens"
Dim EmployeeAddress As String

2.10 Data Types : Data types refer to an extensive system used for declaring variables or functions of
different types. The type of a variable determines how much space it occupies in storage and how the bit pattern
stored is interpreted. VB.Net provides a wide range of data types. The following table shows all the data types
available:

Data Type Storage Allocation Value Range

Boolean Depends on implementing True or False


platform

Byte 1 byte 0 through 255 (unsigned)

Char 2 bytes 0 through 65535 (unsigned)

Date 8 bytes 0:00:00 (midnight) on January 1, 0001 through


11:59:59 PM on December 31, 9999

Decimal 16 bytes 0 through +/-79,228,162,514,264,337,593,543,950,335


(+/-7.9...E+28) with no decimal point; 0 through +/-
7.9228162514264337593543950335 with 28 places to
the right of the decimal

Double 8 bytes -1.79769313486231570E+308 through -


4.94065645841246544E-324, for negative values
4.94065645841246544E-324 through
1.79769313486231570E+308, for positive values
Integer 4 bytes -2,147,483,648 through 2,147,483,647 (signed)

Long 8 bytes -9,223,372,036,854,775,808 through


9,223,372,036,854,775,807(signed)

Object 4 bytes on 32-bit platform Any type can be stored in a variable of type Object
8 bytes on 64-bit platform

Short 2 bytes -32,768 through 32,767 (signed)

Single 4 bytes -3.4028235E+38 through -1.401298E-45 for negative


values;
1.401298E-45 through 3.4028235E+38 for positive
values

String Depends on implementing 0 to approximately 2 billion Unicode characters


platform

2.11 Converting between DataTypes : VB.Net provides the following in-line type conversion
functions:
S.N Functions & Description

1 CBool(expression) : Converts the expression to Boolean data type.

2 CByte(expression) : Converts the expression to Byte data type.

3 CChar(expression) : Converts the expression to Char data type.

4 CDate(expression) : Converts the expression to Date data type

5 CDbl(expression): Converts the expression to Double data type.

6 CDec(expression) : Converts the expression to Decimal data type.

7 CInt(expression) : Converts the expression to Integer data type.

8 CLng(expression) : Converts the expression to Long data type.

9 CObj(expression) : Converts the expression to Object type.

10 CShort(expression) : Converts the expression to Short data type.

11 CSng(expression) : Converts the expression to Single data type.

12 CStr(expression) : Converts the expression to String data type.


Example:
Option Strict On
Module Module1
Sub Main()
Dim dblData As Double
Dim intData As Integer
dblData = 3.14159
intData = CType(dblData, Integer)
System.Console.WriteLine("intData = " & Str(intData))
End Sub
End Module

2.12 Checking Data Types : Visual Basic has a number of data verification functions, and you can
use these functions to interrogate objects and determine their types.
Function Description
IsArray() Returns True if passed an array
IsDate() Returns True if passed a date
IsDBNull() Returns True if passed a database NULL value; that is, a System.DBNull value
IsError() Returns True if passed an error value
IsNumeric() Returns True if passed an numeric value
IsReference() Returns True if passed an Object variable that has no object assigned to it; otherwise, returns
False

2.13 Declaring Arrays and Dynamic Arrays: An array stores a fixed-size sequential
collection of elements of the same type. An array is used to store a collection of data, but it is often more useful
to think of an array as a collection of variables of the same type.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the
highest address to the last element.

Standard Arrays: To declare an array in VB.Net, you use the Dim statement. For example,
Dim intData(30) ' an array of 31 elements
Dim strData(20) As String ' an array of 21 strings
Dim twoDarray(10, 20) As Integer 'a two dimensional array of integers
Dim ranges(10, 100) 'a two dimensional array
You can also initialize the array elements while declaring the array. For example,
Dim intData() As Integer = {12, 16, 20, 24, 28, 32}
Dim names() As String = {"Karthik", "Sandhya", _
"Shivangi", "Ashwitha", "Somnath"}
Dim miscData() As Object = {"Hello World", 12d, 16ui, "A"c}

Dynamic Arrays : Dynamic arrays are arrays that can be dimensioned and re-dimensioned as par the need
of the program. You can declare a dynamic array using the ReDimstatement.
Syntax for ReDim statement: ReDim [Preserve] arrayname(subscripts)
Where,
• The Preserve keyword helps to preserve the data in an existing array, when you resize it.
• arrayname is the name of the array to re-dimension.
• subscripts specifies the new dimension.
Example:
Module arrayApl
Sub Main()
Dim marks() As Integer
ReDim marks(2)
marks(0) = 85
marks(1) = 75
marks(2) = 90
2.14 Handling Strings : In VB.Net, you can use strings as array of characters, however, more
common practice is to use the String keyword to declare a string variable. The string keyword is an alias for
the System.String class.
Creating a String Object
You can create string object using one of the following methods:
• By assigning a string literal to a String variable
• By using a String class constructor
• By using the string concatenation operator (+)
• By retrieving a property or calling a method that returns a string
• By calling a formatting method to convert a value or object to its string representation

Example:
Dim strText As String
Dim myString As String = "Welcome to Visual Basic"

A string can contain up to approximately 2 billion Unicode characters, and it can grow or shrink to match the
data you place in it. There are quite a number of string-handling functions built into Visual Basic.NET.

For example, you use Left, Mid, and Right to divide a string into substrings, you find the length of a string
with Len, and so on.

Besides the string-handling functions that are built into VB .NET, many .NET framework functions are built
into the String class that VB .NET uses.

For example, the Visual Basic UCase function will convert strings to upper case, and so will the String class's
ToUpper method. That means that I can convert a text string to uppercase either by using the VB .NET UCase
function, or the String class's ToUpper method:

String-handling functions and methods :


To do this Use this
Concatenate two strings &, +, String.Concat, String.Join
Compare two strings StrComp, String.Compare, String.Equals, String.CompareTo
Convert strings StrConv, CStr, String. ToString
Copying strings =, String.Copy
Convert to lowercase or Format, Lcase, Ucase, String.Format, String. ToUpper, String. ToLower
uppercase
Convert to and from numbers Str, Val.Format, String.Format
Create string of a repeating Space, String, String.String
character
Create an array of strings from String.Split
one string
Find length of a string Len, String.Length
Format a string Format, String.Format
Get a substring Mid, String.SubString
Insert a substring String.Insert
Justify a string with padding LSet, Rset, String.PadLeft, String.PadRight
Manipulate strings InStr, Left, LTrim, Mid, Right, RTrim, Trim, String.Trim,
String.TrimEnd, String.TrimStart
Remove text Mid, String.Remove
Replace text Mid, String.Replace
Set string comparison rules Option Compare
Search strings InStr, String.Chars, String.IndexOf, String.IndexOfAny,
String.LastIndexOf, String.LastIndexOf Any
Trim leading or trailing spaces LTrim, RTrim, Trim, String.Trim, String.TrimEnd, String.TrimStart
Work with character codes Asc, AscW, Chr

Fixed-Length Strings : VB.NET supports fixed-length strings; for example, this declaration in VB6, which
declares a string of 1000 characters:
Dim strString1 As String * 1000

2.15 Converting Strings to Numbers and Back Again:


You can use the Str to return a string representation of a number, and you use Val to convert a string to a
number. Example :
Module Module1
Sub Main()
Dim strText1 As String = "1234"
Dim intValue1 As Integer
intValue1 = Val(strText1)
strText1 = Str(intValue1)
System.Console.WriteLine(strText1)
End Sub
End Module

2.16 Converting between Characters and Character Codes :


The characters a program stores internally are stored using Unicode character codes; for example, the character
code 65 stands for "A". You can use the Asc and Chr functions:
• Asc— Takes a character and returns its character code. For example, Asc("A") returns 65.
• Chr— Takes a character code and returns the corresponding character. For example, Chr(65) returns
"A".

2.17 Operators : An operator is a symbol that tells the compiler to perform specific mathematical or
logical manipulations. VB.Net is rich in built-in operators and provides following types of commonly used
operators:
Arithmetic Operators : Following table shows all the arithmetic operators supported by VB.Net. Assume
variable A holds 2 and variable B holds 7, then:
Show Examples
Operator Description Example

^ Raises one operand to the power of another B^A will give 49

+ Adds two operands A + B will give 9

- Subtracts second operand from the first A - B will give -5

* Multiplies both operands A * B will give 14

/ Divides one operand by another and returns a floating point result B / A will give 3.5

\ Divides one operand by another and returns an integer result B \ A will give 3

MOD Modulus Operator and remainder of after an integer division B MOD A will give 1

Assignment Operators : There are following assignment operators supported by VB.Net:


Show Examples
Operator Description Example

= Simple assignment operator, Assigns values from right side operands to left C=A+B
side operand will assign
value of A +
B into C

+= Add AND assignment operator, It adds right operand to the left operand and C += A is
assigns the result to left operand equivalent to
C=C+A

-= Subtract AND assignment operator, It subtracts right operand from the left C -= A is
operand and assigns the result to left operand equivalent to
C=C-A

*= Multiply AND assignment operator, It multiplies right operand with the left C *= A is
operand and assigns the result to left operand equivalent to
C=C*A

/= Divide AND assignment operator, It divides left operand with the right C /= A is
operand and assigns the result to left operand (floating point division) equivalent to
C=C/A

\= Divide AND assignment operator, It divides left operand with the right C \= A is
operand and assigns the result to left operand (Integer division) equivalent to
C = C \A

^= Exponentiation and assignment operator. It raises the left operand to the C^=A is
power of the right operand and assigns the result to left operand. equivalent to
C=C^A

&= Concatenates a String expression to a String variable or property and assigns Str1 &= Str2
the result to the variable or property. is same as
Str1 = Str1
& Str2

Comparison Operators : Following table shows all the comparison operators supported by VB.Net.
Assume variable A holds 10 and variable B holds 20, then:
Operator Description Example

= Checks if the values of two operands are equal or not; if yes, then (A = B) is not
condition becomes true. true.

<> Checks if the values of two operands are equal or not; if values are not (A <> B) is true.
equal, then condition becomes true.

> Checks if the value of left operand is greater than the value of right (A > B) is not
operand; if yes, then condition becomes true. true.

< Checks if the value of left operand is less than the value of right operand; (A < B) is true.
if yes, then condition becomes true.

>= Checks if the value of left operand is greater than or equal to the value of (A >= B) is not
right operand; if yes, then condition becomes true. true.

<= Checks if the value of left operand is less than or equal to the value of (A <= B) is true.
right operand; if yes, then condition becomes true.
Apart from the above, VB.Net provides three more comparison operators, which we will be using in
forthcoming chapters; however, we give a brief description here.
• Is Operator - It compares two object reference variables and determines if two object references refer to
the same object without performing value comparisons. If object1 and object2 both refer to the exact
same object instance, result is True; otherwise, result is False.
• IsNot Operator - It also compares two object reference variables and determines if two object references
refer to different objects. If object1 and object2 both refer to the exact same object instance, result
isFalse; otherwise, result is True.
• Like Operator - It compares a string against a pattern.

Logical/Bitwise Operators : Following table shows all the logical operators supported by VB.Net.
Assume variable A holds Boolean value True and variable B holds Boolean value False

Operator Description Example

And It is the logical as well as bitwise AND operator. If both the operands are (A And B)
true, then condition becomes true. This operator does not perform short- is False.
circuiting, i.e., it evaluates both the expressions.

Or It is the logical as well as bitwise OR operator. If any of the two operands is (A Or B) is


true, then condition becomes true. This operator does not perform short- True.
circuiting, i.e., it evaluates both the expressions.
Not It is the logical as well as bitwise NOT operator. Use to reverses the logical Not(A And
state of its operand. If a condition is true, then Logical NOT operator will B) is True.
make false.

Xor It is the logical as well as bitwise Logical Exclusive OR operator. It returns A Xor B is
True if both expressions are True or both expressions are False; otherwise it True.
returns False. This operator does not perform short-circuiting, it always
evaluates both expressions and there is no short-circuiting counterpart of this
operator.

AndAlso It is the logical AND operator. It works only on Boolean data. It performs (A AndAlso
short-circuiting. B) is False.

OrElse It is the logical OR operator. It works only on Boolean data. It performs (A OrElse
short-circuiting. B) is True.

IsFalse It determines whether an expression is False.

IsTrue It determines whether an expression is True.

2.18 Operator Precedence: When expressions contain operators from more than one category, they
are evaluated according to the following rules:
• The arithmetic and concatenation operators have the order of precedence described in the following
section, and all have greater precedence than the comparison, logical, and bitwise operators.
• All comparison operators have equal precedence, and all have greater precedence than the logical and
bitwise operators, but lower precedence than the arithmetic and concatenation operators.
• The logical and bitwise operators have the order of precedence described in the following section, and
all have lower precedence than the arithmetic, concatenation, and comparison operators.
• Operators with equal precedence are evaluated left to right in the order in which they appear in the
expression.

The Arithmetic operators have the highest precedence and are arranged this way, from highest precedence to
lowest:

• Exponentiation (^)
• Negation (-) (for example, -intValue reverses the sign of the value in intValue)
• Multiplication and division (*, /)
• Integer division (\)
• Modulus arithmetic (Mod)
• Addition and subtraction (+,-)

Next come the Concatenation operators:

• String concatenation (+)


• String concatenation (&)

Next come the Comparison operators, which all have the same precedence and are evaluated from left to right
as Visual Basic encounters them:

• Equality (=)
• Inequality (<>)
• Less than, greater than (<,>)
• Greater than or equal to (>=)
• Less than or equal to (<=)
• Like
• Is

Finally come the Logical/Bitwise operators, which have this precedence order, from highest to lowest:

• Negation-(Not)
• Conjunction-(And,AndAlso)
• Disjunction-(Or, OrElse, Xor)

2.19 Commenting Your Code: In general, you should add comments to your code when you can to
make what's going on clearer. Comments in Visual Basic start with an apostrophe (') and make Visual Basic
ignore whatever follows the apostrophe on the line. Example

Module Module1
Sub Main()
'Declare the variables we will use
Dim intGrade1, intGrade2, intGrade3, NumberStudents As Integer
'Fill the variables with data
intGrade1 = 60
intGrade2 = 70
intGrade3 = 80
NumberStudents = 3 'Three students
'Display the average value
System.Console.WriteLine("Average grade = " & _
Str((intGrade1 + intGrade2 + intGrade3) / NumberStudents))
End Sub
End Module

2.20 Making Decisions with If…..Else Statements: An If statement can be followed by an


optional Else statement, which executes when the Boolean expression is false. The syntax of an If...Then... Else
statement in VB.Net is as follows:
If(boolean_expression)Then
'statement(s) will execute if the Boolean expression is true
Else
'statement(s) will execute if the Boolean expression is false
End If

If the Boolean expression evaluates to true, then the if block of code will be executed, otherwise else block of
code will be executed. Flow Diagram:

Example:
Module decisions
Sub Main()
Dim a As Integer = 100
If (a < 20) Then
Console.WriteLine("a is less than 20")
Else
Console.WriteLine("a is not less than 20")
End If
End Sub
End Module

The If...Else If...Else Statement : An If statement can be followed by an optional Else


if...Else statement, which is very useful to test various conditions using single If...Else If statement.
When using If... Else If... Else statements, there are few points to keep in mind.
• An If can have zero or one Else's and it must come after an Else If's.
• An If can have zero to many Else If's and they must come before the Else.
• Once an Else if succeeds, none of the remaining Else If's or Else's will be tested.

The syntax of an if...else if...else statement in VB.Net is as follows:


If(boolean_expression 1)Then
' Executes when the boolean expression 1 is true
ElseIf( boolean_expression 2)Then
' Executes when the boolean expression 2 is true
ElseIf( boolean_expression 3)Then
' Executes when the boolean expression 3 is true
Else
' executes when the none of the above condition is true
End If
Example:
Module decisions
Sub Main()
Dim a As Integer = 100
If (a = 10) Then
Console.WriteLine("Value of a is 10") '
ElseIf (a = 20) Then
Console.WriteLine("Value of a is 20") '
ElseIf (a = 30) Then
Console.WriteLine("Value of a is 30")
Else
Console.WriteLine("None of the values is matching")
End If
End Sub
End Module

2.21 Select Case: A Select Case statement allows a variable to be tested for equality against a list of
values. Each value is called a case, and the variable being switched on is checked for each select case.
The syntax for a Select Case statement in VB.Net is as follows:
Select [ Case ] expression
[ Case expressionlist
[ statements ] ]
[ Case Else
[ elsestatements ] ]
End Select
Where,
• expression: is an expression that must evaluate to any of the elementary data type in VB.Net, i.e.,
Boolean, Byte, Char, Date, Double, Decimal, Integer, Long, Object, SByte, Short, Single, String,
UInteger, ULong, and UShort.
• expressionlist: List of expression clauses representing match values for expression. Multiple expression
clauses are separated by commas.
• statements: statements following Case that run if the select expression matches any clause
in expressionlist.
• elsestatements: statements following Case Else that run if the select expression does not match any
clause in the expressionlist of any of the Case statements.

Flow Diagram:
Example:
Module decisions
Sub Main()
Dim grade As Char
grade = "B"
Select grade
Case "A"
Console.WriteLine("Excellent!")
Case "B", "C"
Console.WriteLine("Well done")
Case "D"
Console.WriteLine("You passed")
Case "F"
Console.WriteLine("Better try again")
Case Else
Console.WriteLine("Invalid grade")
End Select
End Sub
End Module

2.22 Making Selections with Switch and Choose Functions:


The Switch Function : The Switch function evaluates a list of expressions and returns an Object value or an
expression associated with the first expression in the list that is true. Here's the syntax:

Switch(expr-1, value-1[, expr-2, value-2 … [, expr-n, value-n]])

In this case, expr-1 is the first expression to evaluate; if true, Switch returns value-1. If expr-1 is not true but
expr-2 is, Switch returns value-2 and so on.

intAbsValue = Switch(intValue < 0, -1 * intValue, intValue >= 0, intValue)


Tip Using the negation operator, -, you can write -1 * intValue simply as -intValue.
The Choose Function :You use the Choose function to return one of a number of choices based on
an index. Here's the syntax:
Choose(index, choice-1[, choice-2, … [, choice-n]])

If the index value is 1, the first choice is returned, if index equals 2, the second choice is returned, and so on.

strEmployeeName = Choose(intID, "Bob", "Denise", "Ted")


2.23 Do Loop: It repeats the enclosed block of statements while a Boolean condition is True or until the
condition becomes True. It could be terminated at any time with the Exit Do statement. The syntax for this
loop construct is:
Do { While | Until } condition
[ statements ]
[ Continue Do ]
[ statements ]
[ Exit Do ]
[ statements ]
Loop
-or-
Do
[ statements ]
[ Continue Do ]
[ statements ]
[ Exit Do ]
[ statements ]
Loop { While | Until } condition
Flow Diagram:

Example:
Module loops
Sub Main()
Dim a As Integer = 10
'do loop execution
Do
Console.WriteLine("value of a: {0}", a)
a=a+1
Loop While (a < 20)
Console.ReadLine()
End Sub
End Module

2.24 For Loop :It repeats a group of statements a specified number of times and a loop index counts the
number of loop iterations as the loop executes.The syntax for this loop construct is:
For counter [ As datatype ] = start To end [ Step step ]
[ statements ]
[ Continue For ]
[ statements ]
[ Exit For ]
[ statements ]
Next [ counter ]
Flow Diagram:

Example
Module loops
Sub Main()
Dim a As Byte
For a = 10 To 20
Console.WriteLine("value of a: {0}", a)
Next
Console.ReadLine()
End Sub
End Module

2.25 For Each……Next Loop : It repeats a group of statements for each element in a collection.
This loop is used for accessing and manipulating all elements in an array or a VB.Net collection.
The syntax for this loop construct is:
For Each element [ As datatype ] In group
[ statements ]
[ Continue For ]
[ statements ]
[ Exit For ]
[ statements ]
Next [ element ]
Example
Module loops
Sub Main()
Dim anArray() As Integer = {1, 3, 5, 7, 9}
Dim arrayItem As Integer
For Each arrayItem In anArray
Console.WriteLine(arrayItem)
Next
Console.ReadLine()
End Sub
End Module

2.26 While loop : It executes a series of statements as long as a given condition is True.
The syntax for this loop construct is:
While condition
[ statements ]
[ Continue While ]
[ statements ]
[ Exit While ]
[ statements ]
End While
Here, statement(s) may be a single statement or a block of statements. The condition may be any expression,
and true is logical true. The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately following the loop.

Flow Diagram:

Here, key point of the While loop is that the loop might not ever run. When the condition is tested and the
result is false, the loop body will be skipped and the first statement after the while loop will be executed.
Example
Module loops
Sub Main()
Dim a As Integer = 10
While a < 20
Console.WriteLine("value of a: {0}", a)
a=a+1
End While
End Sub
End Module
2.27 With Statement : It is not exactly a looping construct. It executes a series of statements that
repeatedly refers to a single object or structure.
The syntax for this loop construct is:
With object
[ statements ]
End With
Example : showing how to put With to work. Here, I'm use a text box, Text1, in a Windows form program, and
setting its Height, Width, and Text properties in the With statement:

With TextBox1
.Height = 1000
.Width = 3000
.Text = "Welcome to Visual Basic"
End With

2.28 Handling Higher Math: The built-in Visual Basic math functions appear in the following Table

Old New Visual Basic .NET Description


method
Abs System.Math.Abs Yields the absolute value of a given number.
Atn System.Math.Atan Yields a Double value containing the angle whose tangent is the given
number.
Cos System.Math.Cos Yields a Double value containing the cosine of the given angle.
Exp System.Math.Exp Yields a Double value containing e (the base of natural logarithms)
raised to the given power.
Log System.Math.Log Yields a Double value containing the logarithm of a given number.
Round System.Math.Round Yields a Double value containing the number nearest the given value.
Sgn System.Math.Sign Yields an Integer value indicating the sign of a number.
Sin System.Math.Sin Yields a Double value specifying the sine of an angle.
Sqr System.Math.Sqrt Yields a Double value specifying the square root of a number.
Tan System.Math.Tan Yields a Double value containing the tangent of an angle.

To use these functions without qualification, import the System.Math namespace into your project. Here's an
example that uses the Atan method:

Imports System.Math
Module Module1
Sub Main()
System.Console.WriteLine("Pi =" & 4 * Atan(1))
End Sub
End Module
Calculated math functions.
Function Calculate this way
Secant Sec(X) = 1 / Cos(X)
Cosecant Cosec(X) = 1 / Sin(X)
Cotangent Cotan(X) = 1 / Tan(X)
Inverse Sine Arcsin(X) = Atn(X / Sqr(-X * X + 1))
Inverse Cosine Arccos(X) = Atn(-X / Sqr(-X * X + 1)) + 2 * Atn(1)
Inverse Secant Arcsec(X) = Atn(X / Sqr(X * X - 1)) + Sgn((X) - 1) * (2 * Atn(1))
Inverse Cosecant Arccosec(X) = Atn(X / Sqr(X * X - 1)) + (Sgn(X) - 1) * (2 * Atn(1))
Inverse Cotangent Arccotan(X) = Atn(X) + 2 * Atn(1)
Hyperbolic Sine HSin(X) = (Exp(X) - Exp(-X)) / 2
Hyperbolic Cosine HCos(X) = (Exp(X) + Exp(-X)) / 2
Hyperbolic Tangent HTan(X) = (Exp(X) - Exp(-X)) / (Exp(X) + Exp(-X))
Hyperbolic Secant HSec(X) = 2 / (Exp(X) + Exp(-X))
Hyperbolic Cosecant HCosec(X) = 2 / (Exp(X) - Exp(-X))
Hyperbolic Cotangent HCotan(X) = (Exp(X) + Exp(-X)) / (Exp(X) - Exp(-X))
Inverse Hyperbolic Sine HArcsin(X) = Log(X + Sqr(X * X + 1))
Calculated math functions.
Function Calculate this way
Inverse Hyperbolic Cosine HArccos(X) = Log(X + Sqr(X * X - 1))
Inverse Hyperbolic Tangent HArctan(X) = Log((1 + X) / (1 - X)) / 2
Inverse Hyperbolic Secant HArcsec(X) = Log((Sqr(-X * X + 1) + 1) / X)
Inverse Hyperbolic Cosecant HArccosec(X) = Log((Sgn(X) * Sqr(X * X + 1) + 1) / X)
Inverse Hyperbolic Cotangent HArccotan(X) = Log((X + 1) / (X - 1)) / 2
Logarithm to base N LogN(X) = Log(X) / Log(N)

2.29 Handling Dates and Times : Visual Basic has a number of date and time handling functions,
which appear in the Table . You can even add or subtract dates using those functions.

Visual Basic date and time properties.


To do this Use this
Get the current date or time Today, Now, TimeofDay, DateString, TimeString
Perform date calculations DateAdd, DateDiff, DatePart
Return a date DateSerial, DateValue
Return a time TimeSerial, TimeValue
Set the date or time Today, TimeofDay
Time a process Timer

Here's an example in which I'm adding 22 months to 12/31/2001 using DateAdd-you might note in particular
that you can assign dates of the format 12/31/2001 to variables of the Date type if you enclose them inside #
symbols:

Imports System.Math
Module Module1
Sub Main()
Dim FirstDate As Date
FirstDate = #12/31/2001#
System.Console.WriteLine("New date: " & DateAdd_
(DateInterval.Month, 22, FirstDate))
End Sub
End Module

There's something else you should know-the Format function makes it easy to format dates into strings,
including times.

Using Format to display dates and times.


Format Expression Yields this
Format(Now, "M-d-yy") "1-1-03"
Format(Now, "M/d/yy") "1/1/03"
Format(Now, "MM - dd - yy") "01 /01 / 03"
Format(Now, "ddd, MMMM d, yyy") "Friday, January 1, 2003"
Format(Now, "d MMM, yyy") "1 Jan, 2003"
Format(Now, "hh:mm:ss MM/dd/yy") "01:00:00 01/01/03"
Format(Now, "hh:mm:ss tt MM-dd-yy") "01:00:00 AM 01-01-03"

2.30 Handling Financial Data:


Visual Basic financial functions.
To do this Use this
Visual Basic financial functions.
To do this Use this
Calculate depreciation DDB, SLN, SYD
Calculate future value FV
Calculate interest rate Rate
Calculate internal rate of return IRR, MIRR
Calculate number of periods NPer
Calculate payments IPmt, Pmt, PPmt
Calculate present value NPV, PV

2.31 Ending a Program at Any Time : To make an Exit menu item active. You use the End
statement. This statement stops execution of your program; here's an example in which I end the program when
the user types "Stop" (or "stop" or "STOP" and so on):

Module Module1
Sub Main()
Dim strInput As String
Do Until UCase(strInput) = "STOP"
System.Console.WriteLine("What should I do?")
strInput = System.Console.ReadLine()
Loop
End
End Sub
End Module
3. The Visual Basic Language: Procedures , Scope and
Exception Handling
3.1 Sub Procedures and Functions: Sub procedures are procedures that do not return any value.
When the applications start, the control goes to the Main Sub procedure, and it in turn, runs any other
statements constituting the body of the program.
Defining Sub Procedures: The Sub statement is used to declare the name, parameter and the body of a sub
procedure. The syntax for the Sub statement is:
[Modifiers] Sub SubName [(ParameterList)]
[Statements]
End Sub
Where,
• Modifiers: specify the access level of the procedure; possible values are: Public, Private, Protected,
Friend, Protected Friend and information regarding overloading, overriding, sharing, and shadowing.
• SubName: indicates the name of the Sub
• ParameterList: specifies the list of the parameters

Example:The following example demonstrates a Sub procedure CalculatePay that takes two
parameters hours and wages and displays the total pay of an employee:
Module mysub
Sub CalculatePay(ByVal hours As Double, ByVal wage As Decimal)
Dim pay As Double
pay = hours * wage
Console.WriteLine("Total Pay: {0:C}", pay)
End Sub
Sub Main()
CalculatePay(25, 10)
CalculatePay(40, 20)
CalculatePay(30, 27.5)
Console.ReadLine()
End Sub
End Module
Passing Parameters by Value : This is the default mechanism for passing parameters to a method. In this
mechanism, when a method is called, a new storage location is created for each value parameter. The values of
the actual parameters are copied into them. So, the changes made to the parameter inside the method have no
effect on the argument. In VB.Net, you declare the reference parameters using the ByVal keyword. The
following example demonstrates the concept:
Module paramByval
Sub swap(ByVal x As Integer, ByVal y As Integer)
Dim temp As Integer
temp = x ' save the value of x
x = y ' put y into x
y = temp 'put temp into y
End Sub
Sub Main()

swap(a, b)

End Sub
End Module

Passing Parameters by Reference : A reference parameter is a reference to a memory location of a variable.


When you pass parameters by reference, unlike value parameters, a new storage location is not created for these
parameters. The reference parameters represent the same memory location as the actual parameters that are
supplied to the method. In VB.Net, you declare the reference parameters using the ByRef keyword. The
following example demonstrates this:
Module paramByref
Sub swap(ByRef x As Integer, ByRef y As Integer)
Dim temp As Integer
temp = x ' save the value of x
x = y ' put y into x
y = temp 'put temp into y
End Sub
Sub Main()
Dim a As Integer = 100
Dim b As Integer = 200
swap(a, b)
End Sub
End Module

3.2 Understanding Scope : The scope of a declared element is the set of all code that can refer to it
without qualifying its name or making it available through an Imports Statement (.NET Namespace and Type).
An element can have scope at one of the following levels:
Level Description

Block scope Available only within the code block in which it is declared

Procedure scope Available to all code within the procedure in which it is declared

Module scope Available to all code within the module, class, or structure in which it is declared

Namespace scope Available to all code in the namespace in which it is declared

The scope of a variable, sometimes referred to as accessibility of a variable, refers to where the variable can be
read from and/or written to, and the variable's lifetime, or how long it stays in memory. The scope of a
procedure or method refers to where a procedure can be called from or under what context you are allowed to
call a method.There are many different ways you can declare variables and procedures. How you make these
declarations controls the scope of variables and procedures.

Term Used With… Visibility

Public Variables/Properties/Methods/Types Anywhere in or outside of a


project

Private Variables/Properties/Methods/Types Only in the block where defined

Protected Variables/Properties/Methods Can be used in the class where


defined. Can be used within any
inherited class.

Friend Variables/Properties/Methods Can only be accessed by code in


the same project/assembly.

ProtectedFriend Variables/Properties/Methods Combination of Protected and


Friend

3.3 Handling Exceptions : An exception is a problem that arises during the execution of a program.
An exception is a response to an exceptional circumstance that arises while a program is running, such as an
attempt to divide by zero.
Unstructured Exception Handling : The old error-handling mechanism in VB6 and before is now
called unstructured exception handling, and it revolves around the On Error Goto statement. You use this
statement to tell VB .NET where to transfer control to in case there's been an exception, as in this case, where
I'm telling Visual Basic to jump to the label "Handler" if there's been an exception. You create labels in your
code with the label name followed by a colon, and the exception-handling code will follow that label .
The On Error GoTo statement enables exception handling and specifies the location of the exception-handling
code within a procedure. Here's how the On Error GoTo statement works:

On Error { GoTo [ line | 0 | -1 ] | Resume Next }

Here are the parts of this statement:

• GoTo line—Enables the exception-handling code that starts at the line specified in the required line
argument. The line argument is any line label or line number. If an exception occurs, program execution
goes to the given location. (Note that the specified line must be in the same procedure as the On Error
statement.)
• GoTo 0—Disables enabled exception handler in the current procedure and resets it to Nothing.
• GoTo -1—Same as GoTo 0.
• Resume Next—Specifies that when an exception occurs, execution skips over the statement that caused
the problem and goes to the statement immediately following. Execution continues from that point.

Module Module1
Sub Main()
On Error Goto Handler

Exit Sub
Handler:

End Sub
End Module

Structured Exception Handling: Visual Basic also supports structured exception handling. In
particular, Visual Basic uses an enhanced version of the Try…Catch…Finally syntax already supported by
other languages, such as Java. Here's an example that follows our previous example handling a division by zero
exception; I start by creating a Try block—you put the exception-prone code in the Try section and the
exception-handling code in the Catch section:
Module Module1
Sub Main()
Try

Catch e As Exception

End Try
End Sub
End Module

Note the syntax of the Catch statement, which catches an Exception object that I'm naming e. When the code in
the Try block causes an exception, I can use the e.ToString method to display a message:

Module Module1
Sub Main()
Dim int1 = 0, int2 = 1, int3 As Integer
Try
int3 = int2 / int1
System.Console.WriteLine("The answer is {0}", int3)
Catch e As Exception
System.Console.WriteLine(e.ToString)
End Try
End Sub
End Module

Structured exception handling is based on a particular statement, the Try…Catch…Finally statement, which is
divided into a Try block, optional Catch blocks, and an optional Finally block. The Try block contains code
where exceptions can occur, the Catch block contains code to handle the exceptions that occur. If an exception
occurs in the Try block, the code throws the exception—actually an object based on the Visual Basic Exception
class—so it can be caught and handled by the appropriate Catch statement. After the rest of the statement
finishes, execution is always passed to the Finally block, if there is one. Here's what the Try…Catch…Finally
statement looks like in general:
Try
[ tryStatements ]
[Catch [ exception1 [ As type1 ] ] [ When expression1 ]
catchStatements1
[Exit Try] ]
[Catch [ exception2 [ As type2 ] ] [When expression2 ]
catchStatements2
[ Exit Try ] ]

[Catch [ exceptionn [ As typen ] ] [ When expressionn ]
catchStatementsn ]
[ Exit Try ] ]
[ Finally
[ finallyStatements ]
End Try

Here are the parts of this statement:

• Try—Begins the Try block for structured exception handling.


• tryStatements—Sensitive statements where you expect exceptions.
• Catch—If an exception happens in the Try block, the exception is thrown and each Catch statement is
examined in order to determine if it will handle the exception.
• exception—A variable name you give the exception. The value of exception is the value of the thrown
exception.
• type—Specifies the type of the exception you're catching in a Catch statement.
• When—A Catch clause with a When clause will only catch exceptions when expression evaluates to
True.
• expression—An expression used to select exceptions to handle; must be convertible to a Boolean value.
Often used to filter exceptions by number.
• catchStatements—Statements to handle exceptions occurring in the Try block.
• Exit Try—Statement that breaks out of the Try…Catch…Finally structure. Execution is transferred to
the code immediately following the End Try statement. Note that Exit Try is not allowed in Finally
blocks.
• Finally—A Finally block is always executed when execution leaves any part of the Try statement.
• finallyStatements—Statements that are executed after all other exception processing has occurred.

3.4 Creating Sub Procedures : Sub procedures are blocks of code that can organize your code into
single-purpose sections to make programming easier. Unlike functions, Sub procedures do not return values, but
like functions, you can pass values to Sub procedures in an argument list.

You declare Sub procedures with the Sub statement:

[ <attrlist> ] [{ Overloads | Overrides | Overridable | NotOverridable |


MustOverride | Shadows | Shared }]
[{ Public | Protected | Friend | Protected Friend | Private }]
Sub name [(arglist)]
[ statements ]
[ Exit Sub ]
[ statements ]
End Sub

Here are the parts of this statement:

• attrlist-List of attributes for this procedure. You separate multiple attributes with commas.
• Overloads-Specifies that this Sub procedure overloads one (or more) procedures defined with the same
name in a base class. In this case, the argument list must be different from the argument list of every
procedure that is to be overloaded (that is, the lists must differ in the number of arguments, their data
types, or both). You cannot specify both Overloads and Shadows in the same procedure declaration.
• Overrides-Specifies that this Sub procedure overrides a procedure with the same name in a base class.
Note that the number and data types of the arguments must match those of the procedure in the base
class.
• Overridable-Specifies that this Sub procedure can be overridden by a procedure with the same name in
a derived class.
• NotOverridable-Specifies that this Sub procedure may not be overridden in a derived class.
• MustOverride-Specifies that this Sub procedure is not implemented. Instead, this procedure must be
implemented in a derived class. If it is not, that class will not be creatable.
• Shadows-Makes this Sub procedure a shadow of an identically named programming element in a base
class. A shadowed element is unavailable in the derived class that shadows it. You can use Shadows
only at module, namespace, or file level (but not inside a procedure). This means you can declare
shadowing variables in a source file or inside a module, class, or structure, but not inside a procedure.
Note that you cannot specify both Overloads and Shadows in the same procedure declaration.
• Shared-Specifies that this Sub procedure is a shared procedure. As a shared procedure, it is not
associated with a specific instance of a class or structure, and you can call it by qualifying it either with
the class or structure name, or with the variable name of a specific instance of the class or structure.
• Public-Procedures declared Public have public access. There are no restrictions on the accessibility of
public procedures.
• Protected-Procedures declared Protected have protected access. They are accessible only from within
their own class or from a derived class. Protected access can be specified only on members of classes.
• Friend-Procedures declared Friend have friend access. They are accessible from within the program
that contains their declaration and from anywhere else in the same assembly.
• Protected Friend-Procedures declared Protected Friend have both protected and friend accessibility.
They can be used by code in the same assembly, as well as by code in derived classes.
• Private-Procedures declared Private have private access. They are accessible only within their
declaration context, including from any nested procedures.
• name-Name of the Sub procedure.
• arglist-List of expressions (which can be single variables or simple values) representing arguments that
are passed to the Sub procedure when it is called. Multiple arguments are separated by commas. Note
that in VB .NET, if you supply an argument list, you must enclose it in parentheses.
• statements-The block of statements to be executed within the Sub procedure.

Each argument in the arglist part has the following syntax and parts:

[ <attrlist> ] [ Optional ] [{ ByVal | ByRef }] [ ParamArray ] argname[( )]


[ As argtype ] [ = defaultvalue ]

Here are the parts of the arglist:

• attrlist-List of attributes that apply to this argument. Multiple attributes are separated by commas.
• Optional-Specifies that this argument is not required when the procedure is called. Note that if you use
this keyword, all following arguments in arglist must also be optional and be declared using the
Optional keyword. Every optional argument declaration must supply a defaultvalue. Also, Optional
cannot be used for any argument if you also use ParamArray.
• ByVal-Specifies passing by value. In this case, the procedure cannot replace or reassign the underlying
variable element in the calling code (unless the argument is a reference type). ByVal is the default in
Visual Basic.
• ByRef-Specifies passing by reference. In this case, the procedure can modify the underlying variable in
the calling code the same way the calling code itself can.
• ParamArray-Used as the last argument in arglist to indicate that the final argument is an optional array
of elements of the specified type. The ParamArray keyword allows you to pass an arbitrary number of
arguments to the procedure. A ParamArray argument is always passed ByVal.
• argname-Name of the variable representing the argument.
• argtype-This part is optional unless Option Strict is set to On, and holds the data type of the argument
passed to the procedure. Can be Boolean, Byte, Char, Date, Decimal, Double, Integer, Long, Object,
Short, Single, or String; or the name of an enumeration, structure, class, or interface.
• defaultvalue-Required for Optional arguments. Any constant or constant expression that evaluates to
the data type of the argument. Note that if the type is Object, or a class, interface, array, or structure, the
default value can be only Nothing.

Each attribute in the attrlist part has the following syntax and parts:

<attrname [({ attrargs | attrinit })]>

Here are the parts of attrlist:


• attrname-Name of the attribute.
• attrargs-List of positional arguments for this attribute. Multiple arguments are separated by commas.
• attrinit-List of field or property initializers for this attribute. Multiple initializers are separated by
commas.

You call a Sub procedure using the procedure name followed by the argument list. The Exit Sub keywords
cause an immediate exit from a Sub procedure. Finally, End Sub ends the procedure definition

Module Module1
Sub Main()
DisplayMessage("Hello from Visual Basic")
End Sub

Sub DisplayMessage(ByVal strText As String)


System.Console.WriteLine(strText)
End Sub
End Module

3.5 Creating Functions :Unlike Sub procedures (see the previous topic), functions can return values.
You use the Function statement to create a function:

[ <attrlist> ] [{ Overloads | Overrides | Overridable | NotOverridable |


MustOverride | Shadows | Shared }]
[{ Public | Protected | Friend | Protected Friend | Private }] Function
name[(arglist)] [ As type ]
[ statements ]
[ Exit Function ]
[ statements ]
End Function

The various parts of this statement are the same as for Sub procedures (see the previous topic) except for the As
type clause, which specifies the type of the return value from the function; here's how to set the type item:

• type-This is optional unless Option Strict is On. Data type of the value returned by the Function
procedure can be Boolean, Byte, Char, Date, Decimal, Double, Integer, Long, Object, Short, Single,
or String; or the name of an enumeration, structure, class, or interface.

The Return statement simultaneously assigns the return value and exits the function; any number of Return
statements can appear anywhere in the procedure. (You also can mix Exit Function and Return statements.)
Here's an example function-Addem-we saw in the In Depth section of this chapter, which adds two integer
values passed to it:

Module Module1
Sub Main()
Dim intValue As Integer = 2
System.Console.WriteLine("{0}+{1}={2}", _
intValue, intValue, Addem(intValue, intValue))
End Sub

Function Addem(ByVal int1 As Integer, ByVal int2 As Integer) As Long


Return int1 + int2
End Function
End Module

3.6 Commenting Your Procedures: In general, you should add a new comment when you declare
a new and important variable, or if you wish to make clear some implementation method. Ideally, procedures
should only have one purpose, and they should be named clearly enough so that excessive comments are not
needed.
Procedures should begin with a comment describing what the procedure does.

Procedure starting comment block sections.


Section Comment description
heading
Purpose What the procedure does.
Assumptions List of each external variable, control, open file, or other element that is not obvious.
Effects List of each affected external variable, control, or file and the effect it has (only if this is not
obvious).
Inputs Each argument that may not be obvious. Arguments are on a separate line with inline
comments.
Returns Explanation of the values returned by functions.

3.7 Passing a Variable Number of Arguments:Usually, you cannot call a procedure with
more arguments than the procedure declaration specifies. When you need an indefinite number of arguments,
you can declare a parameter array, which allows a procedure to accept an array of values for an argument. You
do not have to know the number of elements in the parameter array when you define the procedure. The array
size is determined by each call to the procedure.

Note: In Visual Basic .NET, ParamArray arguments are always passed using ByVal. All of the arguments in
the array must be of the data type of the ParamArray argument.

Here's an example; pass different numbers of arguments to a Sub procedure, DisplayMessage. As you can see
in the way DisplayMessage is declared, all arguments after the first one go into the parameter array.

Module Module1
Sub Main()
DisplayMessage("First message:", "Hi")
DisplayMessage("Second message:", "Hello", "there")
Dim TextArray() As String = {"Hello", "from", "Visual", _
"Basic"}
DisplayMessage("Third message:", TextArray)
Resume Next
End Sub

Sub DisplayMessage(ByVal Title As String, ByVal ParamArray _


MessageText() As String)
Dim intLoopIndex As Integer
System.Console.WriteLine(Title)
For intLoopIndex = 0 To UBound(MessageText)
System.Console.WriteLine(MessageText(intLoopIndex))
Next intLoopIndex
End Sub
End Module

3.8 Specifying Optional Procedure Arguments : You also can make arguments optional in
VB .NET procedures if you use the Optional keyword when declaring those arguments. Note that if you make
one argument optional, all the following arguments must also be optional, and you have to specify a default
value for each optional argument .You specify a default value with = default_value in the procedure's argument
list.

Module Module1
Sub Main()
DisplayMessage()
End Sub

Sub DisplayMessage(Optional ByVal strText As String = _


"Hello from Visual Basic")
System.Console.WriteLine(strText)
End Sub
End Module

3.9 Preserving a Variable's Values between Procedure Calls : Consider the following
example

Module Module1
Sub Main()
Dim intLoopIndex As Integer, intValue = 0
For intLoopIndex = 0 To 4
intValue = Counter()
Next intLoopIndex
System.Console.WriteLine(intValue)
End Sub

Function Counter() As Integer


Dim intCountValue As Integer
intCountValue += 1
Return intCountValue
End Function
End Module

The problem here is that the counter variable, intCountValue, in the Counter function is reinitialized each time
the Counter function is called (because a new copy of all the variables local to procedures is allocated each
time you call that procedure). The solution is to declare intCountValue as static. This means it will retain its
value between calls to the Counter function. Here's the working code:

Module Module1
Sub Main()
Dim intLoopIndex As Integer, intValue = 0
For intLoopIndex = 0 To 4
intValue = Counter()
Next intLoopIndex
System.Console.WriteLine(intValue)
End Sub

Function Counter() As Integer


Static intCountValue As Integer
intCountValue += 1
Return intCountValue
End Function
End Module

3.10 Creating Procedure Delegates :It's useful to be able to pass the location of a procedure to
other procedures. That location is the address of the procedure in memory, and it's used in VB .NET to create
the callback procedures

Here's an example; in this case, I'll create a delegate for a Sub procedure named DisplayMessage:

Module Module1
Sub Main()

End Sub

Sub DisplayMessage(ByVal strText As String)


System.Console.WriteLine(strText)
End Sub
End Module
Start by declaring the delegate type, which will call SubDelegate1, and creating a delegate called Messager:

Module Module1
Delegate Sub SubDelegate1(ByVal strText As String)

Sub Main()
Dim Messager As SubDelegate1

End Sub

Sub DisplayMessage(ByVal strText As String)


System.Console.WriteLine(strText)
End Sub
End Module

Now use the AddressOf operator to assign the address of DisplayMessage to Messager, and then use
Messager's Invoke method to call DisplayMessage and display a message:

Module Module1
Delegate Sub SubDelegate1(ByVal strText As String)

Sub Main()
Dim Messager As SubDelegate1
Messager = AddressOf DisplayMessage
Messager.Invoke("Hello from Visual Basic")
End Sub

Sub DisplayMessage(ByVal strText As String)


System.Console.WriteLine(strText)
End Sub
End Module

3.11 Creating Properties : Visual Basic objects can have methods, fields, and properties. Using
properties provides you with an interface to set or get the value of data internal to an object. You declare
properties using Get and Set procedures in a Property statement

[ <attrlist> ] [ Default ] [ Public | Private | Protected | Friend |


Protected Friend ] [ ReadOnly | WriteOnly ] [Overloads | Overrides ]
[Overridable | NotOverridable] | MustOverride | Shadows | Shared] Property
varname([ parameter list ]) [ As typename ] [ Implements interfacemember ]
[ <attrlist> ] Get
[ block ]
End Get
[ <attrlist> ] Set(ByVal Value As typename )
[ block ]
End Set
End Property

Here are the parts of this statement that are different from the keywords used in the Sub statement,

• Default—Makes this a default property. Default properties can be set and retrieved without specifying
the property name, and must accept parameters.
• ReadOnly—Specifies that a properties value can be retrieved, but it cannot be the modified. ReadOnly
properties contain Get blocks but no Set blocks.
• WriteOnly—Specifies that a property can be set but its value cannot be retrieved. WriteOnly properties
contain Set blocks but no Get blocks.
• varname—A name that identifies the Property.
• parameter list—The parameters you use with the property. The list default is ByVal.
• typename—The type of the property. If you don't specify a data type, the default type is Object.
• interfacemember—When a property is part of a class that implements an interface, this is the name of
the property being implemented.
• Get—Starts a Get property procedure used to return the value of a property. Get blocks are optional
unless the property is ReadOnly.
• End Get—Ends a Get property procedure.
• Set—Starts a Set property procedure used to set the value of a property. Set blocks are optional unless
the property is WriteOnly. Note that the new value of the property is passed to the Set property
procedure in a parameter named Value when the value of the property changes.
• End Set—Ends a Set property procedure.

Visual Basic passes a parameter named Value to the Set block during property assignments, and the Value
parameter contains the value that was assigned to the property when the Set block was called.

Module Module1
Sub Main()

End Sub
End Module

Module Module2
Private PropertyValue As String
Public Property Prop1() As String
Get
Return PropertyValue
End Get
Set(ByVal Value As String)
PropertyValue = Value
End Set
End Property
End Module

3.12 Raising an Exception Intentionally : You can create an exception intentionally, called
raising an exception, with the Visual Basic Err object's Raise method, which is declared this way internally in
VB .NET:

Raise(ByVal Number As Integer, Optional ByVal Source As Object = Nothing,


Optional ByVal Description As Object = Nothing, Optional ByVal HelpFile As
Object = Nothing, Optional ByVal HelpContext As Object = Nothing)

Here are the arguments for the Raise method:

• Number—Long integer that identifies the nature of the exception.


• Source—String expression naming the object or application that generated the exception; use the form
project.class. (If source is not specified, the name of the current Visual Basic project is used.)
• Description—String expression describing the exception.
• Helpfile—The path to the Help file in which help on this exception can be found.
• Helpcontext—A context ID identifying a topic within helpfile that provides help for the exception.

3.13 Exception Filtering in the Catch Block: Exceptions are based on the Visual Basic
Exception class (which, like all other objects in Visual Basic, is based on the Object class). In general, when
you use Visual Basic statements that are capable of throwing exceptions, the Visual Basic documentation will
tell you what possible exceptions each statement may throw. However, that won't help in tracking down
exceptions that occur when you're just using the general syntax of the language, such as when you divide two
numbers and an overflow exception occurs. To track down what class such an exception corresponds to, you
could take a look at the Visual Basic documentation for the Exception class, which lists the classes derived from
it:

Object
Exception
ApplicationException
CodeDomSerializerException
InvalidPrinterException
IOException
IsolatedStorageException
PathTooLongException
CookieException
ProtocolViolationException
WebException
MissingManifestResourceException
SUDSGeneratorException
SUDSParserException
SystemException
UriFormatException
SoapException

Each derived class itself has many derived classes, and if you keep searching (each class above is a hyperlink in
the documentation, so you just keep clicking), you'll eventually find the OverflowException class, which is
based on the ArithmeticException class, which is based on the SystemException class, which is based on the
Exception class:

Object
Exception
SystemException
ArithmeticException
OverflowException

There is an easier way to do this if you can generate the exception you're anticipating—just use the Exception
class's getType method (such as e.getType) to get the type of the exception as a string.

3.14 Using Multiple Catch Statements : You also can use multiple Catch statements when you
filter exceptions. Here's an example that specifically handles overflow, invalid argument, and argument out of
range exceptions:

Module Module1
Sub Main()
Dim int1 = 0, int2 = 1, int3 As Integer
Try
int3 = int2 / int1
System.Console.WriteLine("The answer is {0}", int3)
Catch e As System.OverflowException
System.Console.WriteLine("Exception: Arithmetic overflow!")
Catch e As System.ArgumentException
System.Console.WriteLine("Exception: Invalid argument value!")
Catch e As System.ArgumentOutOfRangeException
System.Console.WriteLine("Exception: Argument out of range!")
End Try
End Sub
End Module

3.15 Using Finally : The code in the Finally block, if there is one, is always executed in a
Try…Catch…Finally statement, even if there was no exception, and even if you execute an Exit Try statement.
This allows you to deallocate resources and so on; here's an example with a Finally block:

Module Module1
Sub Main()
Dim int1 = 0, int2 = 1, int3 As Integer
Try
int3 = int2 / int1
System.Console.WriteLine("The answer is {0}", int3)
Catch e As System.OverflowException
System.Console.WriteLine("Exception: Arithmetic overflow!")
Catch e As System.ArgumentException
System.Console.WriteLine("Exception: Invalid argument value!")
Catch e As System.ArgumentOutOfRangeException
System.Console.WriteLine("Exception: Argument out of range!")
Finally
System.Console.WriteLine("Execution of sensitive code " & _
"is complete")
End Try
End Sub
End Module

3.16 Throwing an Exception : You can throw an exception using the Throw statement, and you can
also rethrow a caught exception using the Throw statement.

Module Module1
Sub Main()
Try
Throw New OverflowException()
Catch e As Exception
System.Console.WriteLine(e.Message)
End Try
End Sub
End Module

3.17 Throwing a Custom Exception : You can customize the exceptions you throw by creating a
new exception object based on the ApplicationException object.

Module Module1
Sub Main()
Try
Throw New ApplicationException("This is a new exception")
Catch e As Exception
System.Console.WriteLine(e.Message)
End Try
End Sub
End Module

You might also like