unit2chapter2VB
unit2chapter2VB
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.
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.
• 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.
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
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.
• 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
CommandButton Used to carry out the specified action when the user chooses it.
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.
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
• 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…
• 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:
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:
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:
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:
Object 4 bytes on 32-bit platform Any type can be stored in a variable of type Object
8 bytes on 64-bit platform
2.11 Converting between DataTypes : VB.Net provides the following in-line type conversion
functions:
S.N Functions & Description
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:
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.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
/ 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
= 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
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.
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.
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 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
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
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
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.
If the index value is 1, the first choice is returned, if index equals 2, the second choice is returned, and so on.
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
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.
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.
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
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
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.
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:
• 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
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.
• 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-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:
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
3.5 Creating Functions :Unlike Sub procedures (see the previous topic), functions can return values.
You use the Function statement to create a 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
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.
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
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
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
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
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
Module Module1
Delegate Sub SubDelegate1(ByVal strText As String)
Sub Main()
Dim Messager As SubDelegate1
⋮
End Sub
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
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
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:
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