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

Visual Basic Merged

Uploaded by

karansaxena7027
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)
8 views

Visual Basic Merged

Uploaded by

karansaxena7027
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/ 157

Visual Basic (VB)

Visual Basic (VB) is an event-driven programming language and environment from Microsoft that provides
a graphical user interface (GUI) which allows programmers to modify code by simply dragging and
dropping objects and defining their behavior and appearance. VB is derived from the BASIC programming
language and is considered to be event-driven and object-oriented.

VB is intended to be easy to learn and fast to write code with; as a result, it is sometimes called a rapid
application development (RAD) system and is used to prototype an application that will later be written in a
more difficult but efficient language.

The last version of VB, Visual Basic 6, was released in 1998, but has since been replaced by VB .NET,
Visual Basic for applications (VBA) and Visual Stuido .NET. VBA and Visual Studio are the two frameworks
most commonly used today.

Visual Basic features and characteristics


VB is a GUI-based development tool that offers a faster RAD than most other programming languages. VB also
features syntax that is more straightforward than other languages, a visual environment that is easy to understand and
high database connectivity.

Visual Basic was designed to be a complete programming language that contained ordinary features, such
as string processing and computation. The visual environment is characterized by a drag-and-drop feature which
allows programmers to build a user interface that is easy to use, even for developers with minimum experience.

While these features of VB are advantageous, there are others that can have a negative effect. The VB programming
environment requires a large amount of memory, both for the initial installation and to run efficiently afterwards. The
graphical features of the programming tool take up a large amount of space and require a significant amount of
memory.

Furthermore, Visual Basic is not useful when developing programs that require a lot of processing time, like games,
and the use of VB is restricted to Microsoft operating systems (OS).

Finally, with C languages, programmers can feasibly locate and use the defined values for variable data in a computer
program at declaration time. This initialization practice is something that isn't easily done with VB.

How Visual Basic is used


The structure of VB is designed to allow programmers to use the environment to write executable files (exe files).
Also, using VB, developers can create programs that can be utilized as a front end to databases. VB tools can help
programmers develop applications or complete software while still allowing them to modify and revise their work
accordingly.

The most popular type of Visual Basic in use today is VBA. VBA is a version of Visual Basic that can be used to
program Microsoft Office apps, such as Excel and PowerPoint. However, it can only be used to modify existing apps;
VBA cannot be used to create new apps.

Typical users engage VBA to make repeated, everyday tasks less monotonous through the use of macros. Macros
automate almost any activity -- such as performing word and data processing or generating custom charts and tables.
For example, a typical user might write a macro that allows them to create and fill a spreadsheet with a single click.
Computer professionals use VBA and macros in more complicated ways. Programmers will often write macros that
can replicate large portions of code or define specific languages.

Businesses and organizations can use VBA to customize Excel for their unique purposes, such as pulling certain
statistics or information from a spreadsheet. Businesses and organizations can also use VBA externally, or in non-
Microsoft applications, by applying a technology called a component object model (COM) interface that enables
commands to communicate across computer boundaries. This allows VBA to be used on an enterprise-specific
application.

Benefits of Visual Basic


The BASIC programming language, which VB is derived from, is simple and easy to work with, especially when
writing exe files.

However, VB becomes extremely beneficial when used with Microsoft's COM interface. The COM components can
be written in various languages and then integrated using VB. Additionally, VB provides not only a programming
language, but an integrated development environment (IDE) that has been written and optimized to best support RAD.
This allows programmers to easily build GUIs and connect them to functions within the application.

Furthermore, the Visual Basic IDE provides views of the management of the program structure that are easy to
understand.

Overall, VB enables the rapid development of Windows based applications while also assisting in the access of
databases by using ActiveX data objects (ADO) while allowing programmers to use ActiveX control and various
objects.
Difference Between VB.NET and Visual Basic

VB.NET stands for Visual Basic. Network Enabled Technologies. Microsoft released the .NET
platform in 2001, that supports Visual Basic .NET which is an upgrade to the last version of VB
programming language. It is a high-level programming language for the Microsoft .NET
Framework. It is also possible to run VB.NET on Linux and MAC operating systems.

Visual Basic or VB is a programming language was initially released in 1991. It was the first
programming language that directly supported programmable graphical user interface using
language-supplied objects. From that time until 2002, there were 7 other versions released, each
version having features that increased the power of the language.

Difference Between VB.NET and Visual Basic:

Parameters VB .NET Visual Basic

Programming
VB.NET is an object-oriented Visual Basic is Event Driven
Language
programming language. programming language.
Paradigm

IntelliSense VB.NET supports It does not supports IntelliSense


compatibility IntelliSense compatibility. compatibility.

It is a compiled typed
It is an Interpreter based language
Type language

It supports the concept of It does not support the


Multithreaded multithreaded. multithreaded concept.

Type-safe It is a type-safe language. It is not a type-safe language.

In VB.NET , VARIANT and In Visual Basic VARIANT and


CURRENCY variable are CURRENCY, variables are used
Changes in Data removed and a DECIMAL and a DECIMAL variable is not
type variable is introduced. introduced.

Parameter In VB.NET parameters are In Visual Basic parameters are


passing passed by a value. passed by reference.

In VB, data is handled using DAO


In VB.NET, data is handled
protocol, after that RDO, is followed
using ADO.net
Data Handling by ADO.
Parameters VB .NET Visual Basic

Visual Basic is an interpreted


In VB.NET background language in this each statement is
compilation takes place interpreted at a time to be converted
continuously for every valid into object code, then into source
Background statement. code so there is no background
Compilation compilation.

VB.NET uses the Common


Visual Basic uses the common
Runtime Language Runtime
Visual Basic Runtime environment.
Environment environment.

There is no shape control


There is a shape control and line
and line control in VB.NET
control in Visual Basic form.
Forms form.

Short Circuit In VB.NET, Short Circuit In Visual Basic, there is no concept


Logic Logic is available. of Short Circuit Logic.

In VB.NET we can create


different types of applications Visual Basic is not versatile for
such as console applications, creating different types of
web applications, windows applications.
Application applications.
Development
Visual Basic
Visual Basic (VB) is a programming language developed by Microsoft in 1992. The purpose of this language
is to develop an application that can run on different versions of the Windows operating system. A Visual
Basic evolved from Basic Language; Basic language is easier to read than other languages. The final version
of Visual Basic was released in 1998. Microsoft then launched a Visual Basic DotNet ('VB.NET') language,
which is much better than Visual Basic in all aspects such as performance, reliability, working environment,
easy to build, and debugging an application.

Features of Visual Basic

o User Interface design


o Rapid Application Development
o Using this language, you can use internet or intranet services in your application.
o It has powerful database access tools, by which you can easily develop front end applications.
o It also supports ActiveX technology, in which you can access the features of other application in
system application. For example: Microsoft Word, Microsoft Excel, etc.
Visual & Non-Visual Programming
What is VB?

Visual Basic is a third-generation event-driven programming language first released by Microsoft


in 1991. It evolved from the earlier DOS version called BASIC. BASIC means Beginners’ All-
purpose Symbolic Instruction Code. Since then Microsoft has released many versions of Visual
Basic, from Visual Basic 1.0 to the final version Visual Basic 6.0. Visual Basic is a user-friendly
programming language designed for beginners, and it enables anyone to develop GUI window
applications easily.

In 2002, Microsoft released Visual Basic.NET(VB.NET) to replace Visual Basic 6. Thereafter,


Microsoft declared VB6 a legacy programming language in 2008. Fortunately, Microsoft still
provides some form of support for VB6. VB.NET is a fully object-oriented programming language
implemented in the .NET Framework. It was created to cater for the development of the web as
well as mobile applications. However, many developers still favor Visual Basic 6.0 over its
successor Visual Basic.NET.

Visual Programming :

 Visual Programming requires IDE: Integrated Development Environment.


 Visual Programming uses IDE so development of programme can be in done fast even
though you don’t know exact language syntax.
 Visual Programming provides visual expression, highlights errors, suggest available methods
and properties.
 In Visual Programming, you can create programme, by using elements graphically i.e. GUI.
 With Visual Programming, you can drag drop programme elements, can draw, can click, use
menus, forms, dialogue boxes etc.
 Visual programming helps non-programmers to involved in program/logic easily.

Non Visual Programming :

 Non Visual Programming does not require IDE : Integrated Development Environment.
 In Non Visual Programming, there is no IDE, so developer has to be master in language
syntax & fast typing as well for the fast development.
 Non Visual Programming does not provide such features.
 In Non Visual Programming, you have to create programme textually, no GUI is there,
only Text based interface.
 With Non Visual Programming, You have to write down programme in the form of text only.
 Non Visual programming is difficult but also increase you memory power and logic.
Differences between Procedural and Object
Oriented Programming
Procedural Programming

Procedural Programming can be defined as a programming model which is derived from


structured programming, based upon the concept of calling procedure. Procedures, also kn own
as routines, subroutines or functions, simply consist of a series of computational steps to be
carried out. During a program’s execution, any given procedure might be called at any point,
including by other procedures or itself.
Languages used in Procedural Programming:

FORTRAN, ALGOL, COBOL,


BASIC, Pascal and C.

Object-Oriented Programming

Object-oriented programming can be defined as a programming model which is based upon the
concept of objects. Objects contain data in the form of attributes and code in the form of
methods. In object-oriented programming, computer programs are designed using the concept of
objects that interact with the real world. Object-oriented programming languages are various but
the most popular ones are class-based, meaning that objects are instances of classes, which
also determine their types.
Languages used in Object-Oriented Programming:

Java, C++, C#, Python,


PHP, JavaScript, Ruby, Perl,
Objective-C, Dart, Swift, Scala.

Procedural Programming vs Object-Oriented Programming

Below are some of the differences between procedural and object-oriented programming:

Procedural Oriented Programming Object-Oriented Programming

In procedural programming, the program is divided In object-oriented programming, the program is


into small parts called functions. divided into small parts called objects.

Procedural programming follows a top-down Object-oriented programming follows a bottom-up


approach. approach.

There is no access specifier in procedural Object-oriented programming has access specifiers


programming. like private, public, protected, etc.
Procedural Oriented Programming Object-Oriented Programming

Adding new data and functions is not easy. Adding new data and function is easy.

Procedural programming does not have any proper way Object-oriented programming provides data hiding so
of hiding data so it is less secure. it is more secure.

In procedural programming, overloading is not Overloading is possible in object-oriented


possible. programming.

In procedural programming, there is no concept of data In object-oriented programming, the concept of data
hiding and inheritance. hiding and inheritance is used.

In procedural programming, the function is more In object-oriented programming, data is more


important than the data. important than function.

Object-oriented programming is based on the real


Procedural programming is based on the unreal world.
world.

Procedural programming is used for designing Object-oriented programming is used for designing
medium-sized programs. large and complex programs.

Procedural programming uses the concept of procedure Object-oriented programming uses the concept of data
abstraction. abstraction.

Code reusability present in object-oriented


Code reusability absent in procedural programming,
programming.

Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.
What Does Procedural Language Mean?
A procedural language is a type of computer programming language that specifies a series of well-structured steps and
procedures within its programming context to compose a program. It contains a systematic order of statements,
functions and commands to complete a computational task or program.

A procedure is a block of Visual Basic statements enclosed by a declaration statement


(Function, Sub, Operator, Get, Set) and a matching End declaration. All executable statements in Visual Basic
must be within some procedure.

Calling a Procedure
You invoke a procedure from some other place in the code. This is known as a procedure call. When the
procedure is finished running, it returns control to the code that invoked it, which is known as the calling
code. The calling code is a statement, or an expression within a statement, that specifies the procedure by
name and transfers control to it.

Returning from a Procedure


A procedure returns control to the calling code when it has finished running. To do this, it can use a Return
Statement, the appropriate Exit Statement statement for the procedure, or the procedure's End <keyword>
Statement statement. Control then passes to the calling code following the point of the procedure call.

 With a Return statement, control returns immediately to the calling code. Statements following
the Return statement do not run. You can have more than one Return statement in the same
procedure.
 With an Exit Sub or Exit Function statement, control returns immediately to the calling code.
Statements following the Exit statement do not run. You can have more than one Exit statement in
the same procedure, and you can mix Return and Exit statements in the same procedure.
 If a procedure has no Return or Exit statements, it concludes with an End Sub or End Function, End Get,
or End Set statement following the last statement of the procedure body. The End statement returns
control immediately to the calling code. You can have only one End statement in a procedure.

Parameters and Arguments


In most cases, a procedure needs to operate on different data each time you call it. You can pass this
information to the procedure as part of the procedure call. The procedure defines zero or more parameters,
each of which represents a value it expects you to pass to it. Corresponding to each parameter in the
procedure definition is an argument in the procedure call. An argument represents the value you pass to the
corresponding parameter in a given procedure call.
Types of Procedures
Visual Basic uses several types of procedures:

 Sub Procedures perform actions but do not return a value to the calling code.
 Event-handling procedures are Sub procedures that execute in response to an event raised by user
action or by an occurrence in a program.
 Function Procedures return a value to the calling code. They can perform other actions before
returning.

Some functions written in C# return a reference return value. Function callers can modify the return
value, and this modification is reflected in the state of the called object. Starting with Visual Basic 2017,
Visual Basic code can consume reference return values, although it cannot return a value by reference.
For more information, see Reference return values.

 Property Procedures return and assign values of properties on objects or modules.


 Operator Procedures define the behavior of a standard operator when one or both of the operands is
a newly-defined class or structure.
 Generic Procedures in Visual Basic define one or more type parameters in addition to their normal
parameters, so the calling code can pass specific data types each time it makes a call.
Object-Oriented
Visual Basic was Object-Based, Visual Basic .NET is Object-Oriented, which
means that it's a true Object-Oriented Programming Language. Visual Basic .NET
supports all the key OOP features like Polymorphism, Inheritance, Abstraction and
Encapsulation. Lets have a brief overview of OOP before starting OOP with VB. A
major factor in the invention of Object-Oriented approach is to remove some of the
flaws encountered with the procedural approach.

In OOP, data is treated as a critical element and does not allow it to flow freely. It
bounds data closely to the functions that operate on it and protects it from
accidental modification from outside functions. OOP allows decomposition of a
problem into a number of entities called objects and then builds data and
functions around these objects. A major advantage of OOP is code reusability.

Some features of Object Oriented programming are as


follows:
 Emphasis on data rather than procedure
 Programs are divided into Objects
 Data is hidden and cannot be accessed by external functions
 Objects can communicate with each other through functions
 New data and functions can be easily added whenever necessary
 Follows bottom-up approach

Concepts of OOP:
 Objects
 Classes
 Data Abstraction and Encapsulation
 Inheritance
 Polymorphism

Objects

Objects are the basic run-time entities in an object-oriented system. Programming


problem is analyzed in terms of objects and nature of communication between
them. When a program is executed, objects interact with each other by sending
messages. Different objects can also interact with each other without knowing the
details of their data or code.
Classes

A class is a collection of objects of similar type. Once a class is defined, any


number of objects can be created which belong to that class.

Data Abstraction and Encapsulation

Abstraction refers to the act of representing essential features without including


the background details or explanations. Classes use the concept of abstraction and
are defined as a list of abstract attributes.Storing data and functions in a single
unit is encapsulation. Data cannot be accessible to the outside world and only
those functions which are stored in the class can access it.

Inheritance

Inheritance is the process by which objects can acquire the properties of objects of
other class. In OOP, inheritance provides reusability, like, adding additional
features to an existing class without modifying it. This is achieved by deriving a
new class from the existing one. The new class will have combined features of both
the classes.

Polymorphism

Polymorphism means the ability to take more than one form. An operation may
exhibit different behaviors in different instances. The behavior depends on the data
types used in the operation. Polymorphism is extensively used in implementing
Inheritance.

Visual Basic .NET is Object-Oriented. Everything we do in Visual Basic involves


objects in some way or other and everything is based on the Object class. Controls,
Forms, Modules, etc are all types of classes. Visual Basic .NET comes with
thousands of built-in classes which are ready to be used. Let's take a closer look at
Object-Oriented Programming in Visual Basic. We will see how we can create
classes, objects, how to inherit one class from other, what is polymorphism, how to
implement interfaces and so on.

Classes and Objects

Classes are types and Objects are instances of the Class. Classes and Objects are
very much related to each other. Without objects you can't use a class. In Visual
Basic we create a class with the Class statement and end it with End Class. The
Syntax for a Class looks as follows:
Code:
Public Class Test
Variables
Methods
Properties
Events
End Class

The above syntax created a class named Test. To create a object for this class we
use the new keyword and that looks like this: Dim obj as new Test().

Fields, Properties, Methods, and Events are members of the class. They can be
declared as Public, Private, Protected, Friend or Protected Friend. Fields and
Properties represent information that an object contains. Fields of a class are like
variables and they can be read or set directly. For example, if you have an object
named House, you can store the numbers of rooms in it in a field named Rooms. It
looks like this:

Code:
Public Class House
Public Rooms as Integer
End Class

Properties are retrieved and set like fields but are implemented using Property Get
and Property Set procedures which provide more control on how values are set or
returned. Methods represent the object’s built-in procedures. Events allow objects
to perform actions whenever a specific occurrence takes place.

Constructors

A constructor is a special member function whose task is to initialize the objects of


it's class. This is the first method that is run when an instance of a type is created.
A constructor is invoked whenever an object of it's associated class is created. If a
class contains a constructor, then an object created by that class will be initialized
automatically. We pass data to the constructor by enclosing it in the parentheses
following the class name when creating an object. Constructors can never return a
value, and can be overridden to provide custom initializations functionality. In
Visual Basic we create constructors by adding a Sub procedure named New to a
class.

Destructors

A destructor, also know as finalizer, is the last method run by a class. Within a
destructor we can place code to clean up the object after it is used, which might
include decrementing counters or releasing resources. We use Finalize method in
Visual Basic for this and the Finalize method is called automatically when the
.NET runtime determines that the object is no longer required.

When working with destructors we need to use the overrides keyword with Finalize
method as we will override the Finalize method built into the Object class. We
normally use Finalize method to deallocate resources and inform other objects that
the current object is going to be destroyed. Because of the nondeterministic nature
of garbage collection, it is very hard to determine when a class's destructor will be
called.

Inheritance

A key feature of OOP is reusability. It's always time saving and useful if we can
reuse something that already exists rather than trying to create the same thing
again and again. Reusing the class that is tested, debugged and used many times
can save us time and effort of developing and testing it again. Once a class has
been written and tested, it can be used by other programs to suit the program's
requirement. This is done by creating a new class from an existing class. The
process of deriving a new class from an existing class is called Inheritance. The old
class is called the base class and the new class is called derived class. The derived
class inherits some or everything of the base class. In Visual Basic we use the
Inherits keyword to inherit one class from other. The general form of deriving a
new class from an existing class looks as follows:

Code:
Public Class One
---
---
End Class
Public Class Two
Inherits One
---
---
End Class

Using Inheritance we can use the variables, methods, properties, etc, from the base
class and add more functionality to it in the derived class.

Polymorphism

Polymorphism is one of the crucial features of OOP. It means "one name, multiple
forms". It is also called as Overloading which means the use of same thing for
different purposes. Using Polymorphism we can create as many functions we want
with one function name but with different argument list. The function performs
different operations based on the argument list in the function call. The exact
function to be invoked will be determined by checking the type and number of
arguments in the function.

The following code demonstrates the implementation of Polymorphism.

Code:
Module Module1
Sub Main()
Dim two As New One()
WriteLine(two.add(10))
'calls the function with one argument
WriteLine(two.add(10, 20))
'calls the function with two arguments
WriteLine(two.add(10, 20, 30))
'calls the function with three arguments
Read()
End Sub
End Module
Public Class One
Public i, j, k As Integer
Public Function add(ByVal i As Integer) As Integer
'function with one argument
Return i
End Function
Public Function add(ByVal i As Integer, ByVal j As Integer) As Integer
'function with two arguments
Return i + j
End Function
Public Function add(ByVal i As Integer, ByVal j As Integer, ByVal k As Integer) As Integer
'function with three arguments
Return i + j + k
End Function
End Class
Interfaces

Interfaces allow us to create definitions for component interaction. They also


provide another way of implementing polymorphism. Through interfaces, we
specify methods that a component must implement without actually specifying
how the method is implemented. We just specify the methods in an interface and
leave it to the class to implement those methods. Visual Basic .NET does not
support multiple inheritance directly but using interfaces we can achieve multiple
inheritance. We use the Interface keyword to create an interface and implements
keyword to implement the interface. Once you create an interface you need to
implement all the methods specified in that interface.

Abstract Classes

An abstract class is the one that is not used to create objects. An abstract class is
designed to act as a base class (to be inherited by other classes). Abstract class is a
design concept in program development and provides a base upon which other
classes are built. Abstract classes are similar to interfaces. After declaring an
abstract class, it cannot be instantiated on it's own, it must be inherited. Like
interfaces, abstract classes can specify members that must be implemented in
inheriting classes. Unlike interfaces, a class can inherit only one abstract class.
Abstract classes can only specify members that should be implemented by all
inheriting classes.

Creating Abstract Classes

In Visual Basic .NET we create an abstract class by using the MustInherit


keyword. An abstract class like all other classes can implement any number of
members. Members of an abstract class can either be Overridable (all the
inheriting classes can create their own implementation of the members) or they
can have a fixed implementation that will be common to all inheriting members.
Abstract classes can also specify abstract members. Like abstract classes, abstract
members also provide no details regarding their implementation. Only the member
type, access level, required parameters and return type are specified. To declare an
abstract member we use the MustOverride keyword. Abstract members should be
declared in abstract classes. When a class inherits from an abstract class, it must
implement every abstract member defined by the abstract class. Implementation is
possible by overriding the member specified in the abstract class.

Structures

Structures can be defined as a tool for handling a group of logically related data
items. They are user-defined and provide a method for packing together data of
different types. Structures are very similar to Classes. Like Classes, they too can
contain members such as fields and methods. The main difference between classes
and structures is, classes are reference types and structures are value types. In
practical terms, structures are used for smaller lightweight objects that do not
persist for long and classes are used for larger objects that are expected to exist in
memory for long periods. We declare a structure in Visual Basic .NET with the
Structure keyword.

Value Types and Reference Types

Value Types and Reference Types belong to Application data memory and the
difference between them is the way variable data is accessed. In VB .NET we use
the Dim statement to create a variable that represents a value type. For example,
we declare a integer variable with the following statement: Dim x as Integer. The
statement tells the run time to allocate the appropriate amount of memory to hold
an integer variable. The statement creates a variable but does not assign a value to
it. We assign a value to that variable like this: x=55. When a variable of value type
goes out of scope, it is destroyed and it's memory is reclaimed.

Reference Types

Creating a variable of reference type is a two-step process, declare and instantiate.


The first step is to declare a variable as that type. For example, the following
statement Dim Form1 as new System.Windows.Forms.Form tells the run time to
set enough memory to hold a Form variable. The second step, instantiation,
creates the object. It looks like this in code: Form1=New
System.Windows.Forms.Form. A variable of reference type exists in two memory
locations and that's why when that variable goes out of scope, the reference to that
object is destroyed but the object itself is not destroyed. If any other references to
that object exist, the object remains intact. If no references exist to that object then
it is subject to garbage collection.
Visual Basic/Event-Driven Design
INTRODUCTION In Event-Driven design one prepares the program in such a way that certain actions are taken only
when an event occurs at the user's initiative or otherwise such as click of a button, or completion of a time interval
etc.
Visual Basic 6.0 offers a wide variety of events to program. Some of the events are common for most of the controls
whereas some are specific to individual controls. Some most common events are as follows:

1. Click
2. MouseMove
3. KeyPress
In Visual Basic, the strength of any graphical or non-graphical control is measured by the kind of special events it
provides to a program.

Advantages of event-driven programming: Event-driven programming is often termed as unstructured


programming as it can never be said which piece of code will get executed unless we know which event occurred.
But this very fact contributes to the major advantage of event-driven programming. With this approach, we can be
sure of some components of a program (or software for that matter) running successfully while we work on others.
Another advantage associated with it is the convenience offered to both the end-user and the programmer. Events
can be initiated by the user (like clicking a button). So it gives the user a feel of control over the system. On the other
hand, programmer can put some very crucial code for very crucial events such as loading of a form, where several
initializations and checks can be performed.

Procedural, Object-oriented and event driven


Programming Languages (Visual Basic).
Procedural Programming :

Procedural Programming can be defined as a programming model which is derived from structured
programming, based upon the concept of calling procedure. Procedures, also known as routines,
subroutines or functions, simply consist of a series of computational steps to be carried out. During
a program’s execution, any given procedure might be called at any point, including by other
procedures or itself.

Languages used in Procedural Programming:FORTRAN, ALGOL, COBOL, BASIC, Pascal and C.

Procedural Programming Languages:

In procedural programming, program is divided into small parts called functions.


Procedural programming follows top down approach.
There is no access specifier in procedural programming.
Adding new data and function is not easy.
Procedural programming does not have any proper way for hiding data so it is less secure.
In procedural programming, overloading is not possible.
In procedural programming, function is more important than data.
Procedural programming is based on unreal world.
Examples: C, FORTRAN, Pascal, Basic etc.
Object Oriented Programming:

Object oriented programming can be defined as a programming model which is based upon the
concept of objects. Objects contain data in the form of attributes and code in the form of methods.
In object oriented programming, computer programs are designed using the concept of objects that
interact with real world. Object oriented programming languages are various but the most popular
ones are class-based, meaning that objects are instances of classes, which also determine their
types.

Languages used in Object Oriented Programming:Java, C++, C#, Python, PHP, JavaScript.

Object Oriented Programming :

 In object oriented programming, program is divided into small parts called objects.
 Object oriented programming follows bottom up approach.
 Object oriented programming have access specifiers like private, public, protected etc.
 Adding new data and function is easy.
 Object oriented programming provides data hiding so it is more secure.
 Overloading is possible in object oriented programming.
 In object oriented programming, data is more important than function.
 Object oriented programming is based on real world.
 Examples: C++, Java, Python, C# etc.

Event-driven Programming Languages:

Event-driven programming is when a program is designed to respond to user engagement in


various forms. It is known as a programming paradigm in which the flow of program execution is
determined by “events.” Events are any user interaction, such as a click or key press, in response
to prompt from the system. To visualize event programming more clearly, imagine the opposite of
event-programming is a software that requires zero user interaction.

Events are monitored by a code (or function) known as an event listener. If the event listener
detects that an assigned event has occurred, it will trigger a callback function, known as an event
handler, which will perform said event, e.g. clicking (the event) a “print” button (event listener)
activates the actual print process (event handler).
Virtually all object-oriented and visual languages support event-driven programming. Visual Basic,
Visual C++ and Java are examples of such languages. A visual programming IDE such as VB.Net
provides much of the code for detecting events automatically when a new application is created.
The Visual Basic Environment
Welcome to the third Article in our Visual Basic section. Last week we installed Visual Basic. This
week we will be looking at the environment that you are presented with when you start Visual
Basic, and set a few options that will prepare Visual Basic to meet our demands.

Let’s run Visual Basic for the very first time. The first thing you will see is this screen, where you are
presented with a list of various project templates.

For now, select Standard EXE, and click on Open. The next Visual Basic will add a few things for
you, to accomplish the standard setup it needs for creating a Standard Executable (Which
eventually will be a runnable program with a .exe extension).

The Visual Basic Interface

The screen you see now will look more or less similar to this one.

Wow. That’s a lot of weird windows. Let’s go through them one by one. In the lower-right corner,
you will see the Form Layout window.

The Form Layout Window

Using the Form Layout Window, you can choose where your program will essentially show up once
it is completed. As you can see, it already contains a small version of a form, which can be moved
around the screen.

Right-clicking the Form Layout Window will also give you the possibility to select some positions
(In the ‘Startup Position’-sub menu). The Form Layout Window is not something we will be using
often. (Well, I don’t use it often. It’s up to you to decide whether or not you leave it visible, or just
hide it).

The window right above the Form Layout Window is the Properties Window.

The Properties Window

This is one of the windows you will probably use a lot. It shows the properties of the currently
selected object. What is a property, you ask? The definition from MSDN is: “A property is a
characteristic of an object, such as size, caption, or color”.

Let’s look at this a little more in-depth, shall we? Imagine for a second we’re a God. We created a
world, threw in trees, bushes, and what not; added a few animals, and are now working on tossing
in a few people. Every person has a few characteristics: Eye color, hair color, a name, a shoe-size,
etc. With the Properties Window, you can quickly see all the various properties on objects, and set
or change current properties.
The Properties Window is made up out of three elements (As seen in the picture):
# Object Box
# Sort Tabs
# Property List

The Object box provides a list of objects currently in use in the project, of which you can set
properties.

The Sort Tabs provide a quick way of sorting the Property List. You can sort either by category, or
alphabetically. This is really a matter of choice, or habit. Use whichever way you prefer.

The Property List provides a list of all the properties that can be set for the currently selected object.
The left column provides the property name, the right column shows the currently assigned value.

Under the Property List, a short description of the currently selected property is displayed. (You
can turn this off by right-clicking the Property Window, and unchecking the Description option).

Above the Properties Window, we’ll find our good friend the Project Explorer.

The Project Explorer

The Project Explorer shows the different files that make up your project. Notice that in the above
screen shot, I added a few extra files, to show a more extensive window than the one you will
currently see.

On the left side of the screen, you will find the toolbox.

The Toolbox

The toolbox holds various ActiveX controls that you can use in your projects. In addition to the
standard ones you already see, you can also add other controls (that could be provided by
Microsoft, third-parties, or controls that you made yourself).

More on controls next week!

In the middle of the screen, you will find the Form Designer.

The Form Designer

The Form Designer shows you the interface of your application. You can use the Form Designer to
determine exactly what your project is going to look like, which controls will be available, which
text will be displayed where, etc, etc.
This leaves us with two more things to discuss concerning the interface. The toolbar, and the menu,
both of which have a lot in common with standard Windows applications, but offer a few new
functions. Let’s tackle the toolbar first.

The Toolbar

The Toolbar provides a number of icons, some of which you will undoubtedly recognize from
programs as Word, or any other Windows Application.

We’ll briefly describe the various icons here, but won’t go deeper into what they do for now, as we
will get working with that gradually, as we advance more and more into the actual programming
process. You can get little description-labels by hovering the cursor over the icon for a second.

The first three icons are specific to Visual Basic. The left-most one allows you to add other projects
to the project you’re working on, the middle icon adds files to your project, and the right-most one
allows you to create user-menus.

The next few ought to look rather familiar to anyone who worked with Windows before. The first
icon is for Opening a file, the second one for saving a file. The third icon is for cutting, the fourth
one for copying, the fifth one for pasting, and the sixth one is for searching. The two arrows on the
far right are respectively for undoing and redoing operations.

Three VB-specific icons again. They might look familiar however. They highly resemble buttons as
they are used on Stereo / Video equipment. They provide the same functionality as well. The first
one runs a project, the second one pauses it, and the third one aborts (or stops) the project.

These icons are all short-cuts to the various windows we discussed earlier. The first one is the
Project Explorer, the second one the Properties Window, the third one represents the Form Layout
Window.

The fourth one is a new one. It points to the Object Browser which we will discuss in future articles.

The fifth icon is for the Toolbox, and the sixth is a new one again. It points to the Data View
Window, which we will discuss when we get to the article about Connectivity to Databases. (Which
will be a few weeks from now).

The right-most icon the Visual Component Manager; basically a repository database for storing
reusable bits and pieces of code, files, components, etc in.

The last part of the toolbar is for keeping track of the position and size of controls. The leftmost part
is for the position, while the right part lists the size of a control. To see what both do, double-click
on one of the icons on the toolbar, which will make a control be added to your form. Rezise and
move the control on the form, and the numbers will change.

The Menu
The Menu contains a few default Windows menu-items (like file, edit, view, help, etc.), and a few
functions specific to programming (like Debug, Run, Project, etc.).

# File-menu; provides file-related functions. (Open / Save / New / Print)


# Edit-menu; provides edit-related functions (Cut / Paste) as well as some look-up functions.
# View-menu; provides functions to access various Windows.
# Project-menu; provides ways to add files, and edit properties of the current project.
# Format-menu; provides functions to format controls on the form.
# Debug-menu; provides functionality to test your code, as well as tracking down errors.
# Run-menu; provides different ways to start and end a program.
# Query-menu; provides database-functionality. Only available in Enterprise Edition.
# Diagram-menu; provides database-functionality. Only available in Enterprise Edition.
# Tools-menu; offers some nifty tools, like wizards.
# Add-ins-menu; offers ways to integrate various external programs into VB.
# Window-menu; provides functionality to rearrange various Windows in the environment.
# Help-menu; provides… *drum roll* help.

That concludes the description of the environment. I also promised to set a few quick options to
configure Visual Basic, so bear with me for another 5 minutes or so. We’ve done the hardest part;
the next few minutes are peanuts. I’ll just provide the settings here. Why I choose the settings will
be explained in future articles.

Configuring Visual Basic

Click on Tools, and select Options. We’re going to make sure that we reduce the number of errors
we’re going to have to deal with. On the tab ‘Editor’, check the ‘Require Variable Declaration’ box.

On the ‘General’-tab, I’d recommend selecting the ‘Break on Unhandled Errors’ option. This will
make debugging easier.

That’s it! Thanks for sticking with me for so long. In next week’s article, we will discuss the
standard controls, and include a few of them in a project. We’ll take a look at their common
properties, events, and methods, as well as make our first actual program.
Variables in Visual Basic
You often have to store values when you perform calculations with Visual Basic. For example, you might
want to calculate several values, compare them, and perform different operations on them, depending on
the result of the comparison. You have to retain the values if you want to compare them.

Usage
Visual Basic, just like most programming languages, uses variables for storing values. A variable has a name
(the word that you use to refer to the value that the variable contains). A variable also has a data type
(which determines the kind of data that the variable can store). A variable can represent an array if it has to
store an indexed set of closely related data items.

Local type inference enables you to declare variables without explicitly stating a data type. Instead, the
compiler infers the type of the variable from the type of the initialization expression. For more information,
see Local Type Inference and Option Infer Statement.

Assigning Values
You use assignment statements to perform calculations and assign the result to a variable, as the following
example shows.

' The following statement assigns the value 10 to the variable.


applesSold = 10
' The following statement increments the variable.
applesSold = applesSold + 1
' The variable now holds the value 11.

Variables and Properties


Like a variable, a property represents a value that you can access. However, it is more complex than a
variable. A property uses code blocks that control how to set and retrieve its value. For more information,
see Differences Between Properties and Variables in Visual Basic.
Variable Declaration in Visual Basic
You declare a variable to specify its name and characteristics. The declaration statement for variables is
the Dim Statement. Its location and contents determine the variable's characteristics.

For variable naming rules and considerations, see Declared Element Names.

Declaration Levels

Local and Member Variables

A local variable is one that is declared within a procedure. A member variable is a member of a Visual Basic
type; it is declared at module level, inside a class, structure, or module, but not within any procedure
internal to that class, structure, or module.

Shared and Instance Variables

In a class or structure, the category of a member variable depends on whether or not it is shared. If it is
declared with the Shared keyword, it is a shared variable, and it exists in a single copy shared among all
instances of the class or structure.

Otherwise it is an instance variable, and a separate copy of it is created for each instance of the class or
structure. A given copy of an instance variable is available only to the instance of the class or structure in
which it was created. It is independent of a copy of the instance variable in any other instance of the class or
structure.

Declaring Data Type


The As clause in the declaration statement allows you to define the data type or object type of the variable
you are declaring. You can specify any of the following types for a variable:

 An elementary data type, such as Boolean, Long, or Decimal


 A composite data type, such as an array or structure
 An object type, or class, defined either in your application or in another application
 A .NET Framework class, such as Label or TextBox
 An interface type, such as IComparable or IDisposable

You can declare several variables in one statement without having to repeat the data type. In the following
statements, the variables i, j, and k are declared as type Integer, l and m as Long, and x and y as Single:

VBCopy
Dim i, j, k As Integer
' All three variables in the preceding statement are declared as Integer.
Dim l, m As Long, x, y As Single
' In the preceding statement, l and m are Long, x and y are Single.
For more information on data types, see Data Types. For more information on objects, see Objects and
Classes and Programming with Components.

Local Type Inference


Type inference is used to determine the data types of local variables declared without an As clause. The
compiler infers the type of the variable from the type of the initialization expression. This enables you to
declare variables without explicitly stating a type. In the following example, both num1 and num2 are strongly
typed as integers.

VBCopy
Public Sub inferenceExample()

' Using explicit typing.


Dim num1 As Integer = 3

' Using local type inference.


Dim num2 = 3

End Sub

If you want to use local type inference, Option Infer must be set to On. For more information, see Local Type
Inference and Option Infer Statement.

Characteristics of Declared Variables


The lifetime of a variable is the period of time during which it is available for use. In general, a variable exists
as long as the element that declares it (such as a procedure or class) continues to exist. If the variable does
not need to continue existing beyond the lifetime of its containing element, you do not need to do
anything special in the declaration. If the variable needs to continue to exist longer than its containing
element, you can include the Static or Shared keyword in its Dim statement. For more information,
see Lifetime in Visual Basic.

The scope of a variable is the set of all code that can refer to it without qualifying its name. A variable's
scope is determined by where it is declared. Code located in a given region can use the variables defined in
that region without having to qualify their names. For more information, see Scope in Visual Basic.

A variable's access level is the extent of code that has permission to access it. This is determined by the
access modifier (such as Public or Private) that you use in the Dim statement. For more information,
see Access levels in Visual Basic.
Types of Variables
Visual Basic recognizes the following five categories of variables:

 Numeric

 String

 Boolean

 Date

 Object

The two major variable categories are numeric and string. Numeric variables store numbers, and string
variables store text. Object variables can store any type of data. Why bother to specify the type if one type
suits all? On the surface, using object variables might seem like a good idea, but they have their
disadvantages. Integer variables are optimized for storing integers, and date variables are optimized for
storing dates. Before VB can use an object variable, it must determine its type and perform the necessary
conversions. If the variable is declared with a specific type, these conversions are not necessary.

We begin our discussion of variable types with numeric variables. Text is stored in string variables, but
numbers can be stored in many formats, depending on the size of the number and its precision. That’s why
there are many types of numeric variables. The String and Date data types are much richer in terms of the
functionality they expose, and are discussed in more detail in Chapter, ‘‘Handling Strings, Characters, and
Dates.”

Numeric Variables
You’d expect that programming languages would use the same data type for numbers. After all, a number
is a number. But this couldn’t be further from the truth. All programming languages provide a variety of
numeric data types, including the following:

 Integers (there are several integer data types)

 Decimals

 Single, or floating-point numbers with limited precision

 Double, or floating-point numbers with extreme precision

Decimal, Single, and Double are the three basic data types for storing floating-point numbers (numbers with
a fractional part). The Double data type can represent these numbers more accurately than the Single type
and is used almost exclusively in scientific calculations.

The Integer data types store whole numbers. The data type of your variable can make a difference in the
results of the calculations. The proper variable types are determined by the nature of the values they
represent, and the choice of data type is frequently a trade-off between precision and speed of execution
(less-precise data types are manipulated faster). Visual Basic supports the numeric data types shown in
Table 2.1. In the Data Type column, I show the name of each data type and the corresponding keyword in
parentheses.

Integer Variables
There are three types of variables for storing integers, and they differ only in the range of numbers each
can represent. As you understand, the more bytes a type takes, the larger values it can hold. The type of
Integer variable you’ll use depends on the task at hand. You should choose the type that can represent the
largest values you anticipate will come up in your calculations. You can go for the Long type, to be safe, but
Long variables are four times as large as Short variables, and it takes the computer longer to process them.

The statements in Listing 2.1 will help you understand when to use the various Integer data types. Each
numeric data type exposes the MinValue and MaxValue properties, which return the minimum and
maximum values, respectively, that can be represented by the corresponding data type. Values of the Short
(Int16) type can be stored in Integer (Int32) and Long (Int64) variables, but the reverse is not true. If you
attempt to store a Long value to an Integer variable, an error will be generated and the compiler will
underline the offending line with a wiggly line. I have included comments after each statement to explain the
errors produced by some of the statements.

Listing 2.1: Experimentingwith the Ranges of Numeric Variables

Dim shortInt As Int16


Dim Int As Int32
Dim longInt As Int64
Debug.WriteLine(Int16.MinValue)
Debug.WriteLine(Int16.MaxValue)
Debug.WriteLine(Int32.MinValue)
Debug.WriteLine(Int32.MaxValue)
Debug.WriteLine(Int64.MinValue)
Debug.WriteLine(Int64.MaxValue)
shortInt = Int16.MaxValue + 1
' ERROR, exceeds the maximum value of the Short data type
Int = Int16.MaxValue + 1
' OK, is within the range of the Integer data type
Int = Int32.MaxValue + 1
' ERROR, exceeds the maximum value of the Integer data type
Int = Int32.MinValue - 1
' ERROR, exceeds the minimum value of the Integer data type
longInt = Int32.MaxValue + 1
' OK, is within the range of the Long data type
longInt = Int64.MaxValue + 1
' ERROR, exceeds the range of all Integer data typesCode language: VB.NET (vbnet)
The six WriteLine statements will print the minimum and maximum values you can represent with the
various Integer data types. The following statement attempts to assign to a Short integer variable a value
that exceeds the largest possible value you can represent with the Short data type, and it will generate an
error. The editor will underline the incorrect statement, and if you hover the pointer over the statement,
you’ll see the error description: Constant expression not representable in type Short. If you attempt to store
the same value to an Integer variable, there will be no problem because this value is well within the range
of the Integer data type.

The next two statements attempt to store to an Integer variable two values that are also outside of the
range that an integer can represent. The first value exceeds the range of positive values, and the second
exceeds the range of negative values. If you attempt to store these values to a Long variable, there will be
no problem. If you exceed the range of values that can be represented by the Long data type, you’re out of
luck. This value can’t be represented as an integer, and you must store it in one of the variable types
discussed in the next sections.

Object Variables
Variants — variables without a fixed data type— were the bread and butter of VB programmers up to
version 6. Variants are the opposite of strictly typed variables: They can store all types of values, from a
single character to an object. If you’re starting with VB 2008, you should use strictly typed variables.
However, variants are a major part of the history of VB, and most applications out there (the ones you may
be called to maintain) use them. I will discuss variants briefly in this section and show you what was so
good (and bad) about them.

Variants, or object variables, were the most flexible data types because they could accommodate all other
types. A variable declared as Object (or a variable that hasn’t been declared at all) is handled by Visual
Basic according to the variable’s current contents. If you assign an integer value to an object variable,
Visual Basic treats it as an integer. If you assign a string to an object variable, Visual Basic treats it as a
string. Variants can also hold different data types in the course of the same program. Visual Basic performs
the necessary conversions for you.

To declare a variant, you can turn off the Strict option and use the Dim statement without specifying a type,
as follows:

Dim myVarCode language: VB.NET (vbnet)


If you don’t want to turn off the Strict option (which isn’t recommended, anyway), you can declare the
variable with the Object data type:

Dim myVar As ObjectCode language: VB.NET (vbnet)


Every time your code references a new variable, Visual Basic will create an object variable. For example, if
the variable validKey hasn’t been declared, when Visual Basic runs into the following line, it will create a
new object variable and assign the value 002-6abbgd to it:

validKey = "002-6abbgd"Code language: VB.NET (vbnet)


You can use object variables in both numeric and string calculations. Suppose that the variable
modemSpeed has been declared as Object with one of the following statements:

Dim modemSpeed ' with Option Strict = Off


Dim modemSpeed As Object ' with Option Strict = OnCode language: VB.NET (vbnet)
and later in your code you assign the following value to it:

modemSpeed = "28.8"Code language: VB.NET (vbnet)


The modemSpeed variable is a string variable that you can use in statements such as the following:

MsgBox "We suggest a " & modemSpeed & " modem."Code language: VB.NET (vbnet)
This statement displays the following message:

"We suggest a 28.8 modem."Code language: VB.NET (vbnet)


You can also treat the modemSpeed variable as a numeric value with the following statement:
Debug.WriteLine "A " & modemSpeed & " modem can transfer " &
modemSpeed * 1024 / 8 & " bytes per second."Code language: VB.NET (vbnet)
This statement displays the following message:

"A 28.8 modem can transfer 3686.4 bytes per second."Code language: VB.NET (vbnet)
The first instance of the modemSpeed variable in the preceding statement is treated as a string because
this is the variant’s type according to the assignment statement (we assigned a string to it). The second
instance, however, is treated as a number (a single-precision number). Visual Basic converts it to a numeric
value because it’s used in a numeric calculation.

Another example of this behavior of variants can be seen in the following statements:

Dim I As Integer, S As String


I = 10
S = "11"
Debug.WriteLine(I + S)
Debug.WriteLine(I & S)Code language: VB.NET (vbnet)
The first WriteLine statement will display the numeric value 21, whereas the second statement will print the
string 1011. The plus operator (+) tells VB to add two values. In doing so, VB must convert the two strings
into numeric values and then add them. The concatenation operator (&) tells VB to concatenate the two
strings.

Visual Basic knows how to handle object variables in a way that makes sense. The result may not be what
you had in mind, but it certainly is dictated by common sense. If you really want to concatenate the strings
10 and 11, you should use the & operator, which would tell Visual Basic exactly what to do. Quite
impressive, but for many programmers, this is a strange behavior that can lead to subtle errors — and they
avoid it. It’s up to you to decide whether to use variants and how far you will go with them. Sure, you can
perform tricks with variants, but you shouldn’t overuse them to the point that others can’t read your code.

Date Variables
Date and time values are stored internally in a special format, but you don’t need to know the exact format.
They are double-precision numbers: the integer part represents the date, and the fractional part represents
the time. A variable declared as Date with a statement like the following can store both date and time
values:

Dim expiration As Date


The following are all valid assignments:
expiration = #01/01/2008#
expiration = #8/27/2008 6:29:11 PM#
expiration = "July 2, 2008"
expiration = Today()Code language: VB.NET (vbnet)
By the way, the Today() function returns the current date and time, while the Now() function returns the
current date. You can also retrieve the current date by calling the Today property of the Date data type:
Date.Today.

The pound sign tells Visual Basic to store a date value to the expiration variable, just as the quotes tell
Visual Basic that the value is a string. You can store a date as a string to a Date variable, but it will be
converted to the appropriate format. If the Strict option is on, you can’t specify dates by using the Long date
format (as in the third statement of this example).
The date format is determined by the Regional Settings (found in the Control Panel). In the United States,
the format is mm/dd/yy. (In other countries, the format is dd/mm/yy.) If you assign an invalid date to a date
variable, such as 23/04/2002, the statement will be underlined and an error message will appear in the
Task List window. The description of the error is Date constant is not valid.

The Date data type is extremely flexible; Visual Basic knows how to handle date and time values, so you
won’t have to write complicated code to perform the necessary conversions. To manipulate dates and
times, use the members of the Date type, which are discussed in detail in Chapter “Handling Strings,
Characters, and Dates”, or the date and time functions of VB 6, which are still supported by VB 2008.

You can also perform arithmetic operations with date values. VB recognizes your intention to subtract dates
and it properly evaluates their difference. The result is a TimeSpan object, which represents a time interval.
If you execute the following statements, the value 638.08:49:51.4970000 will appear in the Output window:

Dim d1, d2 As Date


d1 = Now
d2 = #1/1/2004#Debug.WriteLine(d1 - d2)Code language: VB.NET (vbnet)
The value of the TimeSpan object represents an interval of 638 days, 8 hours, 49 minutes, and 51.497
seconds.

Data Type Identifiers


Finally, you can omit the As clause of the Dim statement, yet create typed variables, with the variable
declaration characters, or data type identifiers. These characters are special symbols that you append to
the variable name to denote the variable’s type. To create a string variable, you can use this statement:

Dim myText$Code language: VB.NET (vbnet)


The dollar sign signifies a string variable. Notice that the name of the variable includes the dollar sign — it’s
myText$, not myText. To create a variable of a particular type, use one of the data declaration characters
shown in the following table. (Not all data types have their own identifiers.)

Table 2.3 – Data Type Definition Characters

Symbol Data Type Example

$ String A$, messageText$

% Integer (Int32) counter%, var%

& Long (Int64) population&, colorValue&

! Single distance!
Symbol Data Type Example

# Double ExactDistance

@ Decimal Balance@

Using type identifiers doesn’t help to produce the cleanest and easiest-to-read code. They’re relics from
really old versions of BASIC, and if you haven’t used them in the past, there’s no really good reason to start
using them now.
Converting Variable Types
In many situations, you will need to convert variables from one type into another. Table 2.4 shows
the methods of the Convert class that perform data-type conversions.

In addition to the methods of the Convert class, you can still use the data-conversion functions of
VB (CInt() to convert a numeric value to an Integer, CDbl() to convert a numeric value to a Double,
CSng() to convert a numeric value to a Single, and so on), which you can look up in the
documentation. If you’re writing new applications in VB 2008, use the new Convert class to convert
between data types.

To convert the variable initialized as the following

Dim A As IntegerCode language: VB.NET (vbnet)


to a Double, use the ToDouble method of the Convert class:

Dim B As Double
B = Convert.ToDouble(A)Code language: VB.NET (vbnet)
Suppose that you have declared two integers, as follows:

Dim A As Integer, B As Integer


A = 23
B = 7Code language: VB.NET (vbnet)
The result of the operation A / B will be a Double value. The following statement

Debug.Write(A / B)Code language: VB.NET (vbnet)


displays the value 3.28571428571429. The result is a Double value, which provides the greatest
possible accuracy. If you attempt to assign the result to a variable that hasn’t been declared as
Double, and the Strict option is on, then VB 2008 will generate an error message. No other data
type can accept this value without loss of accuracy. To store the result to a Single variable, you
must convert it explicitly with a statement like the following:

Convert.ToSingle(A / B)Code language: VB.NET (vbnet)


You can also use the DirectCast() function to convert a variable or expression from one type to
another. The DirectCast() function is identical to the CType() function. Let’s say the variable A has
been declared as String and holds the value 34.56. The following statement converts the value of
the A variable to a Decimal value and uses it in a calculation:

Dim A As String = "34.56"


Dim B As Double
B = DirectCast(A, Double) / 1.14Code language: VB.NET (vbnet)
The conversion is necessary only if the Strict option is on, but it’s a good practice to perform your
conversions explicitly. The following section explains what might happen if your code relies on
implicit conversions.

Table 2.4 – The Data-Type Conversion Methods of the Convert Class


Method Converts Its Argument To

ToBoolean Boolean

ToByte Byte

ToChar Unicode character

ToDateTime Date

ToDecimal Decimal

ToDouble Double

ToInt16 Short Integer (2-byte integer, Int16)

ToInt32 Integer (4-byte integer, Int32)

ToInt64 Long (8-byte integer, Int64)

ToSByte Signed Byte

CShort Short (2-byte integer, Int16)

ToSingle Single

ToString String
Method Converts Its Argument To

ToUInt16 Unsigned Integer (2-byte integer, Int16)

ToUInt32 Unsigned Integer (4-byte integer, Int32)

ToUInt64 Unsigned Long (8-byte integer, Int64)

Widening and Narrowing Conversions


In some situations, VB 2008 will convert data types automatically, but not always. Let’s say you
have declared and initialized two variables, an Integer and a Double, with the following statements:

Dim count As Integer = 99


Dim pi As Double = 3.1415926535897931Code language: VB.NET (vbnet)
If the Strict option is off and you assign the variable pi to the count variable, the count variable’s
new value will be 3. (The Double value was rounded to an Integer value, according to the variable’s
type.) Although this may be what you want, in most cases it’s an oversight that will lead to incorrect
results.

If the Strict option is on and you attempt to perform the same assignment, the compiler will
generate an error message to the effect that you can’t convert a Double to an Integer. The exact
message is Option Strict disallows implicit conversions from Double to Integer.

When the Strict option is on, VB 2008 will perform conversions that do not result in loss of accuracy
(precision) or magnitude. These conversions are called widening conversions. When you assign an
Integer value to a Double variable, no accuracy or magnitude is lost. This is a widening conversion,
because it goes from a narrower to a wider type.

On the other hand, when you assign a Double value to an Integer variable, some accuracy is lost
(the decimal digits must be truncated). This is a narrowing conversion, because we go from a data
type that can represent a wider range of values to a data type that can represent a narrower range
of values.

Because you, the programmer, are in control, you might want to give up the accuracy —
presumably, it’s no longer needed. Table 2.5 summarizes the widening conversions that VB 2008
will perform for you automatically.

Table 2.5: Visual Basic 2008 Widening Conversions


Original Data Type Wider Data Type

Any type Object

Byte Short, Integer, Long, Decimal, Single, Double

Short Integer, Long, Decimal, Single, Double

Integer Long, Decimal, Single, Double

Long Decimal, Single, Double

Decimal Single, Double

Single Double

Double None

Char String

If the Strict option is on, the compiler will point out all the statements that may cause runtime errors,
and you can reevaluate your choice of variable types. You can also turn on the Strict option
temporarily to see the compiler’s warnings, and then turn it off again.
User-Defined Data Types
In the previous sections, we used variables to store individual values. As a matter of fact, most
programs store sets of data of different types. For example, a program for balancing your
checkbook must store several pieces of information for each check: the check’s number, amount,
date, and so on. All these pieces of information are necessary to process the checks, and ideally,
they should be stored together.

You can create custom data types that are made up of multiple values using structures. A VB
structure allows you to combine multiple values of the basic data types and handle them as a
whole. For example, each check in a checkbook-balancing application is stored in a separate
structure (or record), as shown in Figure 2.3. When you recall a given check, you need all the
information stored in the structure.

Figure 2.3 – Pictorial representation of a structure

To define a structure in VB 2008, use the Structure statement, which has the following syntax:

Structure structureName

Dim variable1 As varType


Dim variable2 As varType
...
Dim variablen As varType

End StructureCode language: VB.NET (vbnet)


varType can be any of the data types supported by the CLR. The Dim statement can be replaced
by the Private or Public access modifiers. For structures, Dim is equivalent to Public.

After this declaration, you have in essence created a new data type that you can use in your
application. structureName can be used anywhere you’d use any of the base types (Integers,
Doubles, and so on). You can declare variables of this type and manipulate them as you
manipulate all other variables (with a little extra typing). The declaration for the CheckRecord
structure shown in Figure 2.3 is as follows:

Structure CheckRecord

Dim CheckNumber As Integer


Dim CheckDate As Date
Dim CheckAmount As Single
Dim CheckPaidTo As String

End StructureCode language: VB.NET (vbnet)


This declaration must appear outside any procedure; you can’t declare a Structure in a subroutine
or function. Once declared, The CheckRecord structure becomes a new data type for your
application.

To declare variables of this new type, use a statement such as this one:

Dim check1 As CheckRecord, check2 As CheckRecordCode language: VB.NET (vbnet)


To assign a value to one of these variables, you must separately assign a value to each one of its
components (they are called fields), which can be accessed by combining the name of the variable
and the name of a field, separated by a period, as follows:

check1.CheckNumber = 275Code language: VB.NET (vbnet)


Actually, as soon as you type the period following the variable’s name, a list of all members to the
CheckRecord structure will appear, as shown in Figure 2.4. Notice that the structure supports a few
members on its own.

Figure 2.4 – Variables of custom types expose their members as properties

You didn’t write any code for the Equals, GetType, and ToString members, but they’re standard
members of any Structure object, and you can use them in your code. Both the GetType and
ToString methods will return a string like ProjectName.FormName + CheckRecord. You can
provide your own implementation of the ToString method, which will return a more meaningful
string:

Public Overrides Function ToString() As String


Return "CHECK # " & CheckNumber & " FOR " &
CheckAmount.ToString("C")
End FunctionCode language: VB.NET (vbnet)
As you understand, structures are a lot like objects that expose their fields as properties and then
expose a few members of their own. The following statements initialize a CheckRecord variable:

check2.CheckNumber = 275
check2.CheckDate = #09/12/2008#
check2.CheckAmount = 104.25
check2.CheckPaidTo = "Gas Co."Code language: VB.NET (vbnet)
You can also create arrays of structures with a declaration such as the following (arrays are
discussed later in this chapter):
Dim Checks(100) As CheckRecordCode language: VB.NET (vbnet)
Each element in this array is a CheckRecord structure and it holds all the fields of a given check.
To access the fields of the third element of the array, use the following notation:

Checks(2).CheckNumber = 275
Checks(2).CheckDate = #09/12/2008#
Checks(2).CheckAmount = 104.25
Checks(2).CheckPaidTo = "Gas Co."Code language: VB.NET (vbnet)

The Nothing Value


The Nothing value is used with object variables and indicates a variable that has not been
initialized. If you want to disassociate an object variable from the object it represents, set it to
Nothing. The following statements create an object variable that references a brush, uses it, and
then releases it:

Dim brush As SolidBrush


brush = New SolidBrush(Color.Blue)
{ use brush object to draw with}
brush = NothingCode language: VB.NET (vbnet)
The first statement declares the brush variable. At this point, the brush variable is Nothing. The
second statement initializes the brush variable with the appropriate constructor (the brush is
initialized to a specific color). After the execution of the second statement, the brush variable
actually represents an object you can draw with in blue. After using it to draw something, you can
release it by setting it to Nothing.

If you want to find out whether an object variable has been initialized, use the Is or IsNot operators,
as shown in the following example:

Dim myPen As Pen


{ more statements here}
If myPen Is Nothing Then
myPen = New Pen(Color.Red)
End IfCode language: VB.NET (vbnet)
The variable myPen is initialized with the New constructor only if it hasn’t been initialized already. If
you want to release the myPen variable later in your code, you can set it to Nothing with the
assignment operator. When you compare an object to Nothing, however, you can’t use the equals
operator; you must use the Is and IsNot operators.

Examining Variable Types


Besides setting the types of variables and the functions for converting between types, Visual Basic
provides the GetType method, which returns a string with the variable’s type (Int32, Decimal, and
so on). Any variable exposes these methods automatically, and you can call them like this:

Dim var As Double


Debug.WriteLine "The variable's type is " & var.GetType.ToStringCode language: VB.NET
(vbnet)
There’s also a GetType operator, which accepts as an argument a type and returns a Type object
for the specific data type. The GetType method and GetType operator are used mostly in If
structures, like the following one:

If var.GetType() Is GetType(Double) Then


{ code to handle a Double value}
End IfCode language: VB.NET (vbnet)
Notice that the code doesn’t reference data type names directly. Instead, it uses the value returned
by the GetType operator to retrieve the type of the class System.Double and then compares this
value to the variable’s type with the Is (or the IsNot) keyword.
The Type Conversion Functions in VB.Net
VB.Net provides the following in-line type conversion functions −

Sr.No. Functions & Description

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

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

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

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

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

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

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

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

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

CSByte(expression)
10
Converts the expression to SByte data type.

CShort(expression)
11
Converts the expression to Short data type.

CSng(expression)
12
Converts the expression to Single data type.

CStr(expression)
13
Converts the expression to String data type.

CUInt(expression)
14
Converts the expression to UInt data type.

CULng(expression)
15
Converts the expression to ULng data type.

CUShort(expression)
16
Converts the expression to UShort data type.

Example
The following example demonstrates some of these functions −

Live Demo
Module DataTypes
Sub Main()
Dim n As Integer
Dim da As Date
Dim bl As Boolean = True
n = 1234567
da = Today

Console.WriteLine(bl)
Console.WriteLine(CSByte(bl))
Console.WriteLine(CStr(bl))
Console.WriteLine(CStr(da))
Console.WriteLine(CChar(CChar(CStr(n))))
Console.WriteLine(CChar(CStr(da)))
Console.ReadKey()
End Sub
End Module

When the above code is compiled and executed, it produces the following result −

True
-1
True
12/4/2012
1
1
Forcing Variable Declarations VB Help
Visual Basic doesn’t enforce variable declaration, which is a good thing for the average programmer. When you want to slap
together a “quick-and-dirty” pro-gram, the last thing you need is someone telling You Ito decide which variables you’re going to
use and to declare them before using them.
But most programmers accustomed to the free format of Visual Basic also carry their habits of quick-and-dirty coding to large
projects. When writing large appli-cations, you will probably find that variable declaration is a good thing. It will help you write
clean code and simplify debugging. Variable declaration eliminates the source of the most common and pesky bugs.
If you have gotten spoiled, you can ask Visual Basic to. enforce variable declaration for you. To do so, place the following
statement in the declarations section of ; a Form or Module:
Option Explicit
This statement tells the compiler to check each variable before using it and to issue an error message if you attempt to use a
variable without declaring it. If you omit the Option Explicit statement, Visual Basic creates variables as needed.
The option Explicit statement must be included in every Module in which you want to enforce variable declaration. If you decide
to declare all variables in your projects, you can ask Visual Basic to insert the Option Explicit statement automatically in every
Module by checking the Require Variable Declaration checkbox in the Options dialog box (choose Tools> Options), as shown in
Figure 3.2.

FIGURE 3.2
Let’s examine the side effects of implicit variable declaration in your application. You could use the following statements to
convert German marks to U.s. dollars:
DM2USD =1.562
USDollars = amount * DM2USD
The first time your code refers to the DM2USD variable name, Visual Basic creates a new variable and then uses it as if it was
declared.
Suppose the variable DM2USD appears in many places in your application. If. in one of these places you type DM2USD instead
of DM2USD and the program doesn’t enforce variable declaration, the compiler will create a new variable, assign it the value
zero, and then use it. Any amount converted with the DM2UDS variable will be zero! If the application enforces variable
declaration, the compiler will complain (the DM2UDS variable hasn’t been declared), and you will catch the error.
Many programmers, though, feel restricted by having to declare variables. Others live by it. Depending on your experiences with
Visual Basic, you can decide for yourself. For a small application, you don’t have to declare variables. It’s too much typing. But
for large applications that may take weeks or months to develop, you should consider variable declaration.
A Variable’s Scope
In addition to its type, a variable also has a scope. The scope of a variable is the section of the application that can see and
manipulate the variable. If a variable is declared within a procedure, only the code in the specific procedure has access to that
variable. This variable doesn’t exist for the rest of the application. When the. variable’s scope is limited to a procedure it’s
called local.
Suppose you’re coding the Click event of a Common button to calculate the sum of all even numbers in the range 0 to 100. One
possibility is the following:
The variables i and Sum are local to the CommandClick() procedure. If you attempt to set the value of the Sum variable from
within another procedure, Visual Basic will create another Sum’variable and use it. But this won’t affect the variable Sum in the
Command_Click() subroutine.
Sometimes, however, you’ll need to use a variable with a broader scope, such as one whose value is available to
all procedures within the same Form or Module. These variables are called Form-wide (or Module-wide) and can be
accessed from within all procedures in a component. In principle; you could declare all variables in the Form’s declaration
section, but this would lead to problems. Every procedure in the Form would have access to the variable, and you would’ need to
be careful not to change the value of a variable without good reason. Variables that are needed by a single procedure (such as
loop counters, for example), should be declared in the procedure that uses them, not as Form variables.
Finally, in some situations the entire application must access a certain variable. In this case, the variable must be declared as
Public. Public variables have a global scope they are visible from any part of the application). To declare a public variable, use
the Public statement in place of the Dim statement. Moreover, public variables may not appear inside procedures. They must be
declared as Form variables or in a Module.
The Lifetime of a Variable
In addition to type and scope, variables have a lifetime, which is the period for which they retain their value. Variables declared
as Public exist for the lifetime the application. Local variables, declared within procedures with the Dim or Private statement, live
as long as the procedure. When the procedure finishes, the local variables cease to exist and the allocated memory is returned to
the system. Of course, the same procedure can be called again” In this case, the local variables are recreated and initialized
again.
You also can force a local variable to preserve its value between procedure calls with the Static keyword. Suppose the user of
your application can enter numeric values at any time. One of the tasks performed by the application is to track the average of
the numeric values. Instead of adding all the values each time the user adds it new value and dividing by the count, you can keep
a running total with the function RunningAvg(), which is shown next.

You must declare the variables CurrentTotal and TotalItems outside the function so that their values are preserved between calls.
Alternatively, you can declare them in the function with the Static keyword:

The advantage of using static variables is that they help you minimize the number of total variables in the application. All you
need is the running average.which the RunningAvg() function provides without making its variables visible to the re~t of the
application. Therefore, you don’t risk changing the variables’ values
from within other procedures.
Variables declared in a Form outside any procedure take effect when the Form is loaded and cease to exist when the Form is
unloaded. If the Form is loaded again, its variables are initialized, as if it’s being loaded for the first time ..
Constants
. .. ,
Some variables don’t change value during the execution of a program. These are constants that appear many times in your code.
For instance, if your program does math calculations, the value of pi (3.14159… ) may appear many times in your code. These
values are best represented by constants. Instead of typing the value 3.14159 over and over again, you can define a constant,
name it pi, and use the name of the constant in your code. The following statement:
Area = 2 * pi * Radius
is much easier to understand· than the equivalent:
Area = 2 * 3.14159 * Radius
You could declare pi as a variable, but constants are preferred for two reasons:
1. Constants don’t change value. This is a safety feature. Once a constant has been declared, you can’t change its value in
subsequent statements, therefore,you can be sure that the value specified in the constant’s declaration will take effect in the
entire program.
2. Constants are processed faster than variables. When the program is running, the values of constants don’t have to be looked up.
The compiler substitutes constant names with their values, and the program executes faster.
The manner in which you declare constants is similar to the manner in which . you declare variables, except that in addition to
supplying the constant’s name you must also supply a value, as follows:
Canst constantname [As type] = value
The As type part of the declaration is optional. If you omit it, the constant’s type is determined by the value you assign to it.
Constants also have a scope and can be Public or Private. The constant pi, for instance, is usually declared in a Module
as Public so that every procedure can access it:
Public Const pi AS Double = 3.14159265358979
The constantname variable is a valid constant name that follows the same rules as variable names. The constant’s value is a
literal value or a simple expression composed of numeric or string constants and operators. You can’t use functions in declaring
variables. One way to define the value of pi is as follows:
pi = 4 * Atn(1)
However, you can’t use this assignment in the constant declaration. You must supply the actual value.
constant van be strings too, much as
Const ExpDate = ’31/12/1997
or:
Const ValidKey = ‘A567dfe’
Visual Basic uses constants extensively to define the various arguments of its methods and the settings of the various control
properties. The value of a Check-Box control, for instance, can be 0 (unchecked), 1(checked), or 2 (grayed). Instead of using
statements like:
Checkl.Value = 0
Check2.Value = 2
use the built-in constants vbUnchecked and vbGrayed:
Checkl.Value – vbUnchecked
Check2.Value – vbGrayed
Visual Basic’s constants are prefixed with vb, indicating that they are Visual Basic constants. The constants vbUnchecked and
vbGrayed are built into the language, and you don’t need to declare them. Their symbolic names make the code much easier to
read and maintain. Avoid the vb prefix when declaring your own constants. Other components of the language use different
prefixes. For example, the Database Access Objects use constants with the prefix.
Constant declarations may include other constants. In math calculations, the value pi is as common as the value 2. * pi. You can
declare these two values as constant:
Public Const pi As Double – 3.141592653SJ979
Public Canst pi2 As Double – 2 * pi
You can also create circular constant defination, such as the following:
Const constant1 = constant * 2
Const constant2 = constant 1/ 2
This circular definition doesn’t lead an, where (none of the constants has a value) and should be avoided.
It’s very unlikely that these two declaration will appear in the same Module, but you may forget how you defined constant1; in
one of the Modules and attempt to define constant2 in terms of constant1 in a not her Module. If this happens, Visual Basic
generates a runtime error. If you declare all your constants in a single Module, they’re easier to maintain and chance.
forcing variable declaration in vb.net
Option Explicit statement ensures whether the compiler requires all variables to be explicitly declared or not
before it use in the program.
Option Explicit [On Off]

The Option Explicit has two modes. On and Off mode. If Option Explicit mode in ON , you have to declare all
the variable before you use it in the program . If not , it will generate a compile-time error whenever a variable
that has not been declared is encountered .If the Option Explicit mode is OFF , Vb.Net automatically create a
variable whenever it sees a variable without proper declaration.

By default the Option Explicit is On

With the Option Explicit On , you can reduce the possible errors that result from misspelled variable names.
Because in Option Explicit On mode you have to declare each variable in the program for storing data.
Take a look at the following programs, it will give you a clear picture of Option Explicit.
The following program is a normal vb.net program , so the default mode of Option Explicit On is using. The
default is Option Explicit On , so we do not need to put it in the source code.
VB.NET Source Code

Public Class Form1


Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim someVariable As String
someVariable = "Option Explicit ON"
MsgBox(someVariable)
End Sub

End Class
VB.NET Operators
In VB.NET programming, the Operator is a symbol that is used to perform various operations on
variables. VB.NET has different types of Operators that help in performing logical and mathematical operations on
data values. The Operator precedence is used to determine the execution order of different Operators in the VB.NET
programming language.

What is VB.NET Operator?


In VB.NET, operator is a special symbol that tells the compiler to perform the specific logical or mathematical
operation on the data values. The data value itself (which can be either a variable or a constant) is called
an operand, and the Operator performs various operations on the operand.

For example: In the expression,

3+2-1

The symbol + and - are the Operators, and the 3, 2, and 1 are operands.

Different Types of VB.NET Operators

Following are the different types of Operators available in VB.NET:

o Arithmetic Operators
o Comparison Operators
o Logical and Bitwise Operators
o Bit Shift Operators
o Assignment Operators
o Concatenation Operators
o Miscellaneous Operators

Arithmetic Operators
The Arithmetic Operators in VB.NET, used to perform mathematical operations such as subtraction, addition,
multiplication, division, etc. on the operands in VB.NET. These are as follows:

Arithmetic Operators in VB.NET

Operators Description Example

^ It is an exponentiation Operator that is used to raises one operand to Y ^ X (X to the


the power of another operand. power Y)

+ The addition Operator is used to add numeric data, as well as X+Y


concatenate two string variables.
- It is a subtraction Operator, which is used to subtract the second X-Y
operand from the first operand.

* The multiplication Operator is used to multiply the operands X*Y

/ It is a division Operator used to divide one operand by another X/Y


operand and returns a floating-point result.

\ It is an integer division Operator, which is similar to division Operator, X\Y


except that it returns an integer result while dividing one operand to
another operand.

Mod It is a modulo (Modulus) Operator, which is used to divide two X Mod Y


operands and returns only a remainder.

Example of Arithmetic Operators in VB.NET:

Arithmetic_Operator.vb

Imports System
Module Arithmetic_Operator
Sub Main()
'Declare a, b And c as integer Data Type()
Dim a, b, c As Integer
Dim d As Single
a = 17
b=4
' Use of + Operator
c=a+b
Console.WriteLine(" Sum of a + b is {0}", c)

'Use of - Operator
c=a-b
Console.WriteLine(" Subtraction of a - b is {0}", c)

'Use of * Operator
c=a*b
Console.WriteLine(" Multiplication of a * b is {0}", c)

'Use of / Operator
d=a/b
Console.WriteLine(" Division of a / b is {0}", d)

'Use of \ Operator
c=a\b
Console.WriteLine(" Similar to division Operator (return only integer value) of a - b is {0}", c)

'Use of Mod Operator


c = a Mod b
Console.WriteLine(" Modulus of a Mod b is {0}", c)

'Use of ^ Operator
c=a^b
Console.WriteLine(" Power of a ^ b is {0}", c)
Console.WriteLine("Press any key to exit...")
Console.ReadKey()
End Sub
End Module

Now compile and execute the above program, by pressing the F5 button or Start button from the Visual Studio; then it
shows the following result:

Comparison Operators
As the name suggests, the Comparison Operator is used to compare the value of two variables or operands for the
various condition such as greater, less than or equal, etc. and returns a Boolean value either true or false based on the
condition.

Operator Description Example

= It checks whether the value of the two operands is equal; If (A = B)


yes, it returns a true value, otherwise it shows False.

<> It is a Non-Equality Operator that checks whether the value of (A <> B), check Non-
the two operands is not equal; it returns true; otherwise, it Equality
shows false.

> A greater than symbol or Operator is used to determine (A > B); if yes, TRUE,
whether the value of the left operand is greater than the
value of the right operand; If the condition is true, it returns Else FALSE
TRUE; otherwise, it shows FALSE value.

< It is a less than symbol which checks whether the value of the (A < B); if the condition is
left operand is less than the value of the right operand; If the true, returns TRUE else
condition is true, it returns TRUE; otherwise, it shows FALSE FALSE
value.

>= It is greater than equal to which checks two conditions A >= B


whether the first operand is greater than or equal to the
second operand; if yes, it returns TRUE; otherwise, it shows
False.

<= This symbol represents less than equal to which determines A <= B
the first operand is less than or equal to the second operand,
and if the condition is true, it returns TRUE; otherwise, it
shows FALSE.

Is The Is Operator is used to validate whether the two objects result = obj1 Is obj2
reference the same variable or object; If the test is true, it
returns True; otherwise, the result is False. In short, it checks
the equality of the objects. An Is Operator is also used to
determine whether the object refers to a valid object.

IsNot The IsNot Operator is similar to Is Operator, except that the Result = obj1 IsNot obj2
two object references the different object; if yes, the result is
True; otherwise, the result is False.

Like The Like Operator is used to check the pattern expression of result = string Like the
string variable; And if the pattern matched, the result is True; pattern, the pattern
otherwise, it returns False. represents the series of
characters used by Like
Operator.

Example of Comparison Operators in VB.NET

Comparison_Operator.vb

Imports System
Module Comparison_Operator
Sub Main()
'declaration of Integer, Object and String Data Type variables
Dim x As Integer = 5
Dim y As Integer = 10
Dim Result, obj, obj2 As Object
Dim str, str2 As String
str = "Apple12345"
str2 = "Apple12345"
obj = 10
obj2 = 20

Console.WriteLine(" Program of Comparison Operator")


'Use of > Operator
Console.WriteLine(" Output of x > y is {0}", x > y)

'Use of < Operator


Console.WriteLine(" Output of x < y is {0}", x < y)

'Use of = Operator
Console.WriteLine(" Output of x = y is {0}", x = y)

'Use of <> Operator


Console.WriteLine(" Output of x <> y is {0}", x <> y)

'Use of >= Operator


Console.WriteLine(" Output of x >= y is {0}", x >= y)

'Use of <= Operator


Console.WriteLine(" Output of x <= y is {0}", x <= y)

'Use of Is Operator
Result = obj Is obj2
Console.WriteLine(" Output of obj Is obj2 is {0}", Result)

'Use of Is Operator
Result = obj IsNot obj2
Console.WriteLine(" Output of obj IsNot obj2 is {0}", Result)

'Use of Like Operator


Result = str Like str2
Console.WriteLine(" Output of str Like str2 is {0}", Result)

Console.WriteLine(" Press any key to exit...")


Console.ReadKey()
End Sub
End Module

Now compile and execute the above code by pressing the F5 button or Start button in Visual studio, it returns the
following output:
Logical and Bitwise Operators
The logical and bitwise Operators work with Boolean (true or false) conditions, and if the conditions become true, it
returns a Boolean value. The following are the logical and bitwise Operators used to perform the various logical
operations such as And, Or, Not, etc. on the operands (variables). Suppose there are two operand A and B, where A is
True, and B is False.

Operator Description Example

And The And Operator represents, whether both the operands are true; the (A And B),
result is True. result = False

Or It is an Or Operator that returns a true value; if anyone operand is true (A Or B), result
from both the operands. = True

Not The Not Operator is used to reverse the logical condition. For example, Not A
if the operand's logic is True, it reveres the condition and makes it False.
Or

Not(A And B) is
True

Xor It is an Exclusive OR Operator that represents, whether both the A Xor B is True
expression is true or false, the result is True; otherwise, the result is
False.

AndAlso It is a logical AND Operator that performs short-circuit operation on the A AndAlso B =
variables, and if both the operands are true, the result is True else the False
result is False.

OrElse It is a logical OR Operator that perform short-circuit operation on A OrElse B =


Boolean data. If anyone of the operand is true, the result is True else the True
result is False.

IsFalse The IsFalse Operator is used to determine whether an expression is


False.
IsTrue The IsTrue Operator is used to determine whether an expression is True.

Example of Logical and Bitwise Operator:

Logic_Bitwise.vb

Imports System
Module Logic_Bitwise
Sub Main()
Dim A As Boolean = True
Dim B As Boolean = False
Dim c, d As Integer
c = 10
d = 20

'Use of And Operator


If A And B Then
Console.WriteLine(" Operands A And B are True")
End If

'Use of Or Operator
If A Or B Then
Console.WriteLine(" Operands A Or B are True")
End If

'Use of Xor Operator


If A Xor B Then
Console.WriteLine(" Operands A Xor B is True")
End If

'Use of And Operator


If c And d Then
Console.WriteLine(" Operands c And d is True")
End If

'Use of Or Operator
If c Or d Then
Console.WriteLine(" Operands c Or d is True")
End If

'Use of AndAlso Operator


If A AndAlso B Then
Console.WriteLine(" Operand A AndAlso B is True")
End If

'Use of OrElse Operator


If A OrElse B Then
Console.WriteLine(" Operand A OrElse B is True")
End If

'Use of Not Operator


If Not (A And B) Then
Console.WriteLine(" Output of Not (A And B) is True")
End If

Console.WriteLine(" Press any key to exit?")


Console.ReadKey()
End Sub
End Module

Now compile and execute the above code by pressing the F5 button or Start button in Visual studio, it returns the
following output:

Bit Shift Operators


The Bit Shit Operators are used to perform the bit shift operations on binary values either to the right or to the left.

Bit Shift operations in VB.NET

Operator Description

AND The Binary AND Operator are used to copy the common binary bit in the result if the bit
exists in both operands.

OR The Binary OR Operator is used to copy a common binary bit in the result if the bit found
in either operand.
XOR The Binary XOR Operator in VB.NET, used to determine whether a bit is available to copy in
one operand instead of both.

Not The binary NOT Operator is also known as the binary Ones' Compliment Operator, which is
used to flip binary bits. This means it converts the bits from 0 to 1 or 1 to 0 binary bits.

<< The Binary Left Shift Operator is used to shift the bit to the left side.

>> The Binary Right Shift Operator is used to shift the bit to the right side.

Example of Bit Shift Operator in VB.NET:

BitShift_Operator.vb

Imports System
Module Bitshift_Operator
Sub Main()
Dim x, y, z As Integer
x = 12
y = 25
Dim a, b As Double
a = 5 ' a = 5(00000101)
b = 9 ' b = 9(00001001)

' Use of And Operator


z = x And y
Console.WriteLine(" BitShift Operator x And y is {0}", z)

'Use of Or Operator
z = x Or y
Console.WriteLine(" BitShift Operator x Or y is {0}", z)

z = x Xor y
Console.WriteLine(" BitShift Operator x Xor y is {0}", z)

z = Not y
Console.WriteLine(" BitShift Operator Not y is {0}", z)

'Use of << Left-Shift Operator


' Output is 00001010
Console.WriteLine(" Bitwise Left Shift Operator - a<<1 = {0}", a << 1)

'Output is 00010010
Console.WriteLine(" Bitwise Left Shift Operator - b<<1 = {0}", b << 1)

'Use of >> Right-Shift Operator


'Output is 00000010
Console.WriteLine(" Bitwise Right Shift Operator - a>>1 = {0}", a << 1)

'Output is 00000100
Console.WriteLine(" Bitwise Right Shift Operator - b>>1 = {0}", a << 1)

Console.WriteLine(" Press any key to exit...")


Console.ReadKey()
End Sub
End Module

Now compile and execute the above code by pressing the F5 button or Start button in Visual studio, it returns the
following output:

Assignment Operators
The Assignment Operators are used to assign the value to variables in VB.NET.

Assignment Operators in VB.NET

Operator Description Example

= It is a simple assignment Operator used to assign a right- X = 5, X assign a value 5


side operand or value to a left side operand. X = P + Q, (P + Q) variables
or value assign to X.

+= An Add AND assignment Operator is used to add the value X += 5, which means
of the right operand to the left operand. And the result is X= X+5 ( 5 will add and
assigned to the left operand. assign to X and then result
saved to Left X operand)

-= It is a Subtract AND assignment Operator, which subtracts X -= P, which is same as X =


the right operand or value from the left operand. And then, X-P
the result will be assigned to the left operand.

*= It is a Multiply AND assignment Operator, which multiplies X *= P, which is same as X =


the right operand or value with the left operand. And then, X-P
the result will be assigned to the left operand.

/= It is a Divide AND assignment Operator, which divides the X /= P, which is same as X =


left operand or value with the right operand. And then, the X-P
result will be assigned to the left operand (in floating-point).

\= It is a Divide AND assignment Operator, which divides the X \= P, which is same as X =


left operand or value with the right operand. And then, the X-P
result will be assigned to the left operand (in integer-point
division).

^= It is an expression AND assignment Operator, which raises X ^= P, which is same as X


the left operand or value to the right operand's power. And =X^P
then, the result will be assigned to the left operand.

&= It is a concatenate string assignment Operator used to bind Str &= name, which is same
the right-hand string or variable with the left-hand string or as Str = Str & name
variable. And then, the result will be assigned to the left
operand.

Example of Assignment Operator in VB.NET:

Assign_Operator.vb

Imports System
Module Assign_Operator
Sub Main()
'Declare variable and b As Integer
Dim A As Integer = 5
Dim B As Integer
Dim Str, name As String
name = "come"
Str = "Wel"

'Use of = Operator
B=A
Console.WriteLine(" Assign value A to B is {0}", B)

'Use of += Operator
B += A
Console.WriteLine(" Output of B += A is {0}", B)
'Use of -= Operator
B -= A
Console.WriteLine(" Output of B -= A is {0}", B)

'Use of *= Operator
B *= A
Console.WriteLine(" Output of B *= A is {0}", B)

'Use of /= Operator
B /= A
Console.WriteLine(" Output of B /= A is {0}", B)

'Use of = Operator
B \= A
Console.WriteLine(" Output of B \= A is {0}", B)

'Use of ^= Operator
B ^= A
Console.WriteLine(" Output of B ^= A is {0}", B)

'Use of &= Operator


Str &= name
Console.WriteLine(" Output of Str &= name is {0}", Str)

Console.WriteLine(" Press any key to exit...")


Console.ReadKey()
End Sub
End Module

Now compile and execute the above code by pressing the F5 button or Start button in Visual studio, it returns the
following output:
Concatenation Operators
In VB.NET, there are two concatenation Operators to bind the operands:

Operator Description Example

& It is an ampersand symbol that is used to bind two or more operand Result = Wel
together. Furthermore, a nonstring operand can also be concatenated & come,
with a string variable ( but in that case, Option Strict is on). Result =
Welcome

+ It is also used to add or concatenate two number or string. Result = Wel


+ come,
Result =
Welcome

Example of Concatenation Operators in VB.NET.

MyProgram.vb

Imports System
Module MyProgram
Sub Main()
Dim str As String = "Wel"
Dim str2 As String = "come"
Dim str3 As String = " "
Dim str4 As String = "to JavatPoint"
Dim result As String
Dim result2 As String
result = str & str2
Console.WriteLine(" Result = str & str2 gives = {0}", result)
result2 = str + str2 + str3 + str4
Console.WriteLine(" Result = str + str2 + str3 +str4 gives = {0}", result2.ToString)
Console.ReadLine()
End Sub
End Module

Now compile and execute the above code by pressing the F5 button or Start button in Visual studio, it returns the
following output:

Miscellaneous Operators
There are some important Operator in VB.NET

Operator Description Example

Await An Await Operator is used in an operand to Dim output as out = Await


suspend the execution of an asynchronous AsyncMethodThatReturnsResult() Await
method or lambda expression until the AsyncMethod()
awaited task completes.

AddressOf The AddressOf Operator is used to provide AddHandler Button2.Click, AddressOf


a reference to the address of a procedure. Button2_Click

GetType A GetType Operator is used to retrieve the MsgBox(GetType(String).ToString())


type of the specified object. In addition, the
retrieved object type provides various
information such as methods, properties,
and events.

Function It defines the lambda expression, which Dim mul2 = Function(num As Integer) num
Expression declares the parameter and code. A * 4
Lambda expression is a function that is Console.WriteLine(mul2(4))
used to calculate and return value without
defining the name.

If The If Operator using short circuit Dim a = -4


evaluation to conditionally return a single Console.WriteLine(If (a >= 0,
object value from two defined object "Positive", "Negative"))
values. The If Operator can be used with
two or three defined arguments.

Example of Miscellaneous Operators in VB.NET.

Misc_Operator.vb
Imports System
Module Misc_Operator
Sub Main()
' Initialize a variable
Dim a As Integer = 50
' GetType of the Defined Type
Console.WriteLine(GetType(Double).ToString())
Console.WriteLine(GetType(Integer).ToString())
Console.WriteLine(GetType(String).ToString())
Console.WriteLine(GetType(Single).ToString())
Console.WriteLine(GetType(Decimal).ToString())

'Use of Function()
Dim multiplywith10 = Function(sum As Integer) sum * 10
Console.WriteLine(multiplywith10(10))
Console.WriteLine(If(a >= 0, "Negative", "Positive"))

Console.WriteLine(" Press any key to exit...")


Console.ReadLine()

End Sub
End Module

Now compile and execute the above code by pressing the F5 button or Start button in Visual studio, it returns the
following output:
VB.NET Control Statements
In VB.NET, the control statements are the statements that controls the execution of the program on the
basis of the specified condition. It is useful for determining whether a condition is true or not. If the
condition is true, a single or block of statement is executed. In the control statement, we will use if- Then, if
Then Else, if Then ElseIf and the Select case statement.

We can define more than one condition to be evaluated by the program with statements. If the defined
condition is true, the statement or block executes according to the condition, and if the condition is false,
another statement is executed.

The following figure shows a common format of the decision control statements to validate and execute a
statement:

The above diagram shows that if the defined condition is true, statement_1 will be executed, and if the
condition is false, statement_2 will be executed.

VB.NET provides the following conditional or decision-making statements.

o If-Then Statement
o If-Then Else Statement
o If-Then ElseIf Statement
o Select Case Statement
o Nested Select Case Statements

If-Then Statement
The If-Then Statement is a control statement that defines one or more conditions, and if the particular
condition is satisfied, it executes a piece of information or statements.

Syntax:

If condition Then
[Statement or block of Statement]
End If
In If-Then Statement, the condition can be a Boolean, logical, or relational condition, and the statement can
be single or group of statements that will be executed when the condition is true.

Example 1: Write a simple program to print a statement in VB.NET.

Module1.vb

Module Module1
' Declaration of variable str
Dim str As String = "JavaTpoint"
Sub Main()
' if str equal to "JavaTpoint", below Statement will be executed.
If str = "JavaTpoint" Then
Console.WriteLine("Welcome to the JavaTpoint")
End If
Console.WritLine("press any key to exit?")
Console.ReadKey()
End Sub
End Module

Now compile and execute the above program by clicking on the Start or F5 button, it shows the following
output:

As we can see in the above example, if the value of str is equal to JavaTpoint, the condition is true, and it
prints the Statement.

Example 2: Write a program to print a number is greater than another number in VB.NET.

if_statment2.vb

Module if_statement2
Sub Main()
?Definition of variables
Dim no1, no2 As Integer
Console.WriteLine("Enter any two number:")
no1 = Console.ReadLine() ?read no1 from user
no2 = Console.ReadLine() ?read no2 from user
If no1 > no2 Then
Console.WriteLine("First number is greater than second number")
End If
If no1 < no2 Then
Console.WriteLine("Second number is greater than First number")
End If
Console.WriteLine("press any key to exit...")
Console.ReadKey()
End Sub
End Module

Now compile and execute the above program by clicking on the Start or F5 button, it shows the following
output:

In the above program, we enter two numbers to find the greater number using the relational operator. And if
the first number is greater than the other, the first statement is executed; otherwise, the second statement
will be executed.

If-Then-Else Statement
The If-Then Statement can execute single or multiple statements when the condition is true, but when the
expression evaluates to false, it does nothing. So, here comes the If-Then-Else Statement. The IF-Then-Else
Statement is telling what If condition to do when if the statement is false, it executes the Else statement.
Following is the If-Then-Else statement syntax in VB.NET as follows:

Syntax:

If (Boolean_expression) Then
'This statement will execute if the Boolean condition is true
Else
'Optional statement will execute if the Boolean condition is false
End If

Flow chart
The above diagram represents that if the Boolean expression (condition) is true, the if statement will execute,
and if the Boolean expression is false, Else code or statement will be executed. After that, the control
transfer to the next statement, which is immediately after the If-Then-Else control statement.

Example 1: Write a program to check whether the number is even or odd.

If_Else_statment.vb

Module If_Else_statement
Sub Main()
Dim num As Integer
Console.WriteLine("Enter the Number")
num = Console.ReadLine() 'read data from console

If (num Mod 2 = 0) Then ' if condition is true, print the if statement


Console.WriteLine("It is an even number")

Else 'otherwise, Else statement is executed.


Console.WriteLine("It is an odd number")
End If

Console.WriteLine("press any key to exit...")


Console.ReadKey()
End Sub
End Module

Now compile and execute the above program by clicking on the Start or F5 button, it shows the following
output:
Example 2: Write a program to print the larger and smaller of the two numbers.

if_else_statment2.vb

Module if_else_statement2
Sub Main()
Dim a As Integer
Dim b As Integer
Console.WriteLine("Enter the first number : ")
a = Console.ReadLine()

Console.WriteLine("Enter the second number : ")


b = Console.ReadLine()

If a > b Then
Console.WriteLine(" larger number = {0} and smaller number = {1} ", a, b)
Else
Console.WriteLine(" larger number = {0} and smaller number = {1} ", b, a)
End If

Console.WriteLine("press any key to exit...")


Console.ReadKey()
End Sub
End Module

Now compile and execute the above program by clicking on the Start or F5 button, it shows the following
output:
VB.NET If-Then-ElseIf statement
The If-Then-ElseIf Statement provides a choice to execute only one condition or statement from multiple
statements. Execution starts from the top to bottom, and it checked for each If condition. And if the
condition is met, the block of If the statement is executed. And if none of the conditions are true, the
last block is executed. Following is the syntax of If-Then-ElseIf Statement in VB.NET as follows:

Syntax

If(condition 1)Then
' Executes when condition 1 is true
ElseIf( condition 2)Then
' Executes when condition 2 is true
ElseIf( boolean_expression 3)Then
' Executes when the condition 3 is true
Else
' executes the default statement when none of the above conditions is true.
End If

Flowchart

The following diagram represents the functioning of the If-Else-If Statement in the VB.NET programming
language.

If this condition is true in the flowchart of the if-else-if statement, the statement is executed within the if
block. If the condition is not true, it passes control to the next ElseIf condition to check whether the
condition is matched. And if none of the conditions are matched, the else block is executed.

Example 1: Write a program to show the uses of If... ElseIf statements.

if_elseIf.vb

Module if_elseIf
Sub Main()
Dim var1 As Integer
Console.WriteLine(" Input the value of var1: ")
var1 = Console.ReadLine()
If var1 = 20 Then
'if condition is true then print the following statement'
Console.WriteLine(" Entered value is equal to 20")
ElseIf var1 < 50 Then
Console.WriteLine(" Entered value is less than 50")

ElseIf var1 >= 100 Then


Console.WriteLine(" Entered value is greater than 100")
Else
'if none of the above condition is satisfied, print the following statement
Console.WriteLine(" Value is not matched with above condition")
End If
Console.WriteLine(" You have entered : {0}", var1)
Console.WriteLine(" press any key to exit...")
Console.ReadKey()
End Sub
End Module

Now compile and execute the above program by clicking on the Start or F5 button, it shows the following
output:

Example 2: Write a program to use the If-Then-ElseIf Statement for calculating the division obtained by the
student. Also, take the marks obtained by the student in 5 different subjects from the keyboard.

if_elseIf2.vb

Module If_elseIf2
Sub Main() ' execution start from Main() method
Dim m1, m2, m3, m4, m5, per As Integer
Console.WriteLine("Enter marks in five subjects ")
' Read the marks of five subject
m1 = Console.ReadLine()
m2 = Console.ReadLine()
m3 = Console.ReadLine()
m4 = Console.ReadLine()
m5 = Console.ReadLine()
per = (m1 + m2 + m3 + m4 + m5) / 5
If (per >= 70) Then
'if condition is true, print the first division
Console.WriteLine(" First division")
ElseIf (per >= 60) Then
'if ElseIf condition is true, print the second division
Console.WriteLine(" Second division")
ElseIf (per >= 50) Then
'if ElseIf condition is true, print the third division
Console.WriteLine(" Third division")
ElseIf (per >= 40) Then
'if ElseIf condition is true, print only pass with grace
Console.WriteLine(" Only Pass with Grace")
Else
'if none of the condition is true, print the Failed
Console.WriteLine(" Failed")
End If
Console.WriteLine("press any key to exit...")
Console.ReadKey()
End Sub

End Module

Now compile and execute the above program by clicking on the Start or F5 button, it shows the following
output:
Select Case Statement
In VB.NET, the Select Case statement is a collection of multiple case statements, which allows executing a
single case statement from the list of statements. A selected case statement uses a variable to test for
equality against multiple cases or statements in a program. If the variable is matched with any test cases,
that statement will be executed. And if the condition is not matched with any cases, it executes the default
statement.

Using the select case statement in VB.NET programming, you can replace the uses of multiple If-Then-Else If
statement from the program for better readability and easy to use.

Syntax

Following is the syntax of the Select Case statement in VB.NET, as follows:

Select Case [variable or expression]


Case value1 'defines the item or value that you want to match.
// Define a statement to execute

Case value2 'defines the item or value that you want to match.
// Define a statement to execute

Case Else
// Define the default statement if none of the conditions is true.
End Select

Furthermore, you can also set more than one condition in a single case statement, such as:

Select Case Variable / expression


Case value1
Statement1

Case value2, value3


Statement2

Case Else
// define the default statement if none of the condition is true
End Select

Flowchart of Select Case Statement

The following flowchart represents the functioning of the Select case statement in the VB.NET programming
language.
In Flowchart, the Select Case statement represents the evaluating of the process start from top to bottom. If
the expression or value is matched with the first select case, statement -1 is executed else the control
transfer to the next case for checking whether the expression is matching or not. Similarly, it checks all Select
case statements for evaluating. If none of the cases are matched, the Else block statement will be executed,
and finally, the Select Case Statement will come to an end.

Example 1: Write a program to display the Days name using the select case statement in VB.NET.

Select_case.vb

Imports System
Module Select_case
Sub Main()
'define a local variable.
Dim Days As String
Days = "Thurs"
Select Case Days
Case "Mon"
Console.WriteLine(" Today is Monday")
Case "Tue"
Console.WriteLine(" Today is Tuesday")
Case "Wed"
Console.WriteLine("Today is Wednesday")
Case "Thurs"
Console.WriteLine("Today is Thursday")
Case "Fri"
Console.WriteLine("Today is Friday")
Case "Sat"
Console.WriteLine("Today is Saturday")
Case "Sun"
Console.WriteLine("Today is Sunday")
Case Else
Console.WriteLine(" You have typed Something wrong")

End Select
Console.WriteLine("You have selected : {0}", Days)
Console.WriteLine("Press any key to exit...")
Console.ReadLine()
End Sub
End Module

Now compile and execute the above program by clicking on the Start or F5 button, it shows the following
output:

In the select case statement, the value of Days "Thurs" will compare all the available select cases' values in a
program. If a value matched with any condition, it prints the particular statement, and if the value is not
matched with any select case statement, it prints the default message.

Example 2: Write a program to perform an arithmetic operation using the Select case statement in VB.NET.

Operation.vb

Operation.vb

Imports System
Module Operation
Sub main()
'declaration of the variables
Dim num1, num2, sum As Integer
Dim def As Char
'initialization of num1 and num2 variable
num1 = 2
num2 = 6
Console.WriteLine(" Want to perform any operation?")
Console.WriteLine(" A for Addition")
Console.WriteLine(" S for Subtraction")
Console.WriteLine(" M for Multiplication")
Console.WriteLine(" D for Division")
Console.WriteLine(" Please enter any input")
def = Console.ReadLine()
Select Case def
Case "A"
'perform Addition
sum = num1 + num2
Console.WriteLine(" Addition of two number is :{0}", sum)
Case "S"
'perform Subtraction
sum = num2 - num1
Console.WriteLine(" Subtraction of two number is :{0}", sum)
Case "M"
'perform Multiplication
sum = num1 * num2
Console.WriteLine(" Multiplication of two number is :{0}", sum)
Case "D"
'Peform Division
sum = num2 / num1
Console.WriteLine(" Division of two number is :{0}", sum)
Case Else
'If none of the operation matched, call default statement
Console.WriteLine(" Please enter only define operation With Capital letter")
End Select
Console.WriteLine("Press any key to exit...")
Console.ReadKey()
End Sub
End Module

Now compile and execute the above program by clicking on the Start or F5 button, it shows the following
output:
In the above example, we defined Select with multiple case statements, and if the user-defined input is
matched with any defined case statement, it executes that statement. And if the condition is not matched
with any case, it executes a default statement in VB.NET.

Here, we provide 'M' as input, which checks all case statements, and if any case is matched with M, it
executes the statement within the respective Case statement.

VB.NET Nested Select Case statements


When a Select Case statement is written inside the body of another Select Case statement is called
a nested Select Case statement.

Syntax:

Select Case "num"


' code to be executed if num = 1
Case 1
' nested Select case
Select Case n

' code to be executed if n = 5


Case 5
Statement 1

' code to be executed if n = 10


Case 10
Statement 2

' code to be executed if n = 15


Case 15
Statement 3

' code to be executed if n doesn't match with any cases.


Case Else
Statement

' code to be executed if num = 2


Case 2
Statement 2

' code to be executed if num = 3


Case 3
Statement 3
' code to be executed if num doesn't match with any cases.
Case Else
Statement

Example 1: Write a program to use a nested select case statement in VB.NET.

Module1.vb

Module Module1

Sub Main()

Dim x As Integer = 10, y As Integer = 5


Select Case x

Case 10
Console.WriteLine("X Value: 10")

Select Case y
Case 5
Console.WriteLine("Nested Switch Value: 5")

Select Case y - 2
Case 3
Console.WriteLine("Another Nested Switch Value: 3")

End Select
End Select

Case 15
Console.WriteLine("X Value: 15")

Case 20
Console.WriteLine("X Value: 20")

Case Else
Console.WriteLine("Not Known")

End Select
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module

Now compile and execute the above program by clicking on the Start or F5 button, it shows the following
output:

Example 2: Write a program to use the nested select case statement in VB.NET.

nested_selectcase.vb

Imports System
Module nested_selectcase
Sub Main()
Dim num As Integer
Dim str As String
str = "F"

Console.WriteLine(" Enter only First three number like 1, 2, 3")


num = Console.ReadLine() 'take input from the user
Select Case num
Case 1
Console.WriteLine(" You are in block 1")
Console.WriteLine("Only First two letter such as A and B")

str = Console.ReadLine()
Select Case str
Case "A", "a"
Console.WriteLine(" This is a VB.NET Tutorial")
Case "B", "b"
Console.WriteLine(" Welcome to the JavaTpoint")
Case Else
Console.WriteLine(" Something is wrong")
End Select
Case 2
Console.WriteLine(" You are in block 2")
Console.WriteLine("Only First two letter such as C and D")
str = Console.ReadLine()
Select Case str
Case "C", "c"
Console.WriteLine(" Welcome to the World!")
Case "D", "d"
Console.WriteLine(" Want to go in Heaven")
Case Else
Console.WriteLine(" Something is wrong")
End Select

Case 3
Console.WriteLine(" You are in block 3")
Console.WriteLine("Only First two letter such as E and F")
str = Console.ReadLine()
Select Case str
Case "E", "e"
Console.WriteLine(" VB.NET is a programming language to develop web, window, and console-
based application. ")
Case "F", "f"
Console.WriteLine(" You have to basic knowledge of c and c++")
Case Else
Console.WriteLine(" Something is wrong")
End Select
Case Else
Console.WriteLine(" Something is wrong")
End Select
Console.ReadLine()
End Sub
End Module

Now compile and execute the above program by clicking on the Start or F5 button, it shows the following
output:
In the above example, we have only defined the first three numbers 1-3 and if the number matches to any
case statement, the select statement is executed. Here, we have entered 2 that is matched with case 2 and it
executes a block as shown above. And this block executes the statement "Only the First two letters such as C
and D". Therefore, we enter a letter D, letter D is matched with the nested select case statement, and if a
match is found, it executes the select case statement as shown above.
Visual Basic – Messages and data input/output
Introduction
One way for a user to communicate with a procedure is via a dialogue box. The easiest
way to do this in VB is to use one of the pre-defined ones. VB has two kinds, a Message
box and an Input box.

Message box
The MsgBox function displays a message, waits for the user to click a button and returns
a value indicating which button has been chosen. The simplest MsgBox contains only a
message string and an OK button. The general syntax is
MsgBox(prompt [,buttons] [,title]),
where the quantities within [] are optional arguments, with
prompt: string expression displayed in the message (max length 1024 characters)
buttons: numerical expression that is sum of values specifying the type of buttons
to display,
title: string expression displayed in the title bar.
Some of the button values are given below. (For a full list see the Help file).
Value Constant Display
0 vbOKOnly OK button only
1 vbOKCancel OK and Cancel buttons
3 vbYesNoCancel Yes, No and Cancel buttons
4 vbYesNo Yes and No buttons
32 vbQuestion Query icon
48 vbExclamation Warning message icon
0 vbDefaultButton1 First button is default
256 vbDefaultButton2 Second button is default
512 vbDefaultButton3 Third button is default

The value returned by the MsgBox function depends on the button pressed. Some values
are listed below.
Button selected Value Constant
OK 1 vbOK
Cancel 2 vbCancel
Yes 6 vbYes
No 7 vbNo

The MsgBox function can be used as a simple debug tool. To display the contents of
variable variDisplay then use
MsgBox “Contents of variDisplay “ & variDisplay
which creates a message made from concatenating the text Contents of
variDisplay with the data in the variable variDisplay.

1
The example below displays a message box with two buttons, Yes and No, with No as the
default response. The value returned by the MsgBox function depends on the button
pressed by the user.
msg = “Do you want to continue?”
boxButtons = vbYesNo + vbDefaultButton2
msgTitle = “Processing mode”
response = MsgBox(msg, boxButtons, msgTitle)
If response = vbYes Then
msg = “clicked YES”
Else
msg = “Clicked No or pressed ENTER”
End If
MsgBox msg

Data input and output


A procedure often needs some data on which it applies its actions. A Function procedure
will usually get its input data from its arguments and returns a value in its name. A Sub
procedure could get its input from arguments but it doesn’t return a value, yet it needs to
return data somehow. One method is for the data to be taken from, or put into cells of a
spreadsheet. For example
Activeworkbook.Sheets(1).Range(“A1”).Value = 10
puts the value 10 into cell A1 of the current worksheet. Likewise the statement
xVal = ActiveSheet.Range(“B2”).Value
assigns to the variable xVal in the code the contents of cell B2.

The previous technique presupposes that the values of the data are know in advance and
have been entered into the spreadsheet BEFORE the procedure is run. The InputBox
function creates and displays a simple dialogue box that contains a prompt, an edit box,
and OK and Cancel buttons. You use this box to allow the user to input data at run-time.
The format of the InputBox function is
InputBox(Prompt, [,title] [,default] [,xpos] [,ypos])
with
prompt := a string expression displayed in the box,
Optional arguments
title:= a string expression displayed in the dialogue box’s title bar. If
omitted nothing is displayed.
default:= default response if no input provided
xpos, ypos specify the horizontal and vertical position of the box. If omitted
the box is centred horizontally and about one-third of the way
down the screen.

A simple example is
radius = InputBox(“Enter radius of circle”, “Circle _
radius”)

2
which will display a dialogue box with a title “Circle radius” and a message “Enter radius
of circle” and wait for the user to enter a value.

The InputBox Method (of the Application object) works like the InputBox function but
the method also allows you specify the data type. This enable you to enter a range, e.g.
A1:A10. If data entered is of the wrong type Excel displays an error message. The
format to use is
Application.InputBox(prompt,title,default,left,top,type)
The arguments, prompt, title and default are as for the InputBox function. The
arguments, left, top, and type are optional, (left and top specify the horizontal and
vertical postion from the top left of the screen in point units (=1/72.27 inch)), type
specifies the data type. If type is omitted the method returns text). Type has the
following values,
Value Description
0 a formula
1 a number
2 text (string)
4 logical
8 cell reference ( a range)
16 error value
64 an array of values
Note, type = 1 + 2 accepts text or number.
The code below asks the user to specify a range to search and a search value. The search
range must be a valid range, e.g. sheet!A1:A10, and the search value is a number.
Sub CountEntries()
Dim allCount As Integer, rangeToSearch As Object
Dim searchValue, c
cellCount = 0
Set rangeToSearch = Application.InputBox( _
Prompt: = “Enter range to search”, _
Type: = 8)
‘ type 8 means entry must be a range object
searchValue = Application.InputBox( _
Prompt: = “Search for value”, _
Type: = 1)
‘ type 1 means a number
If searchValue = False Then Exit Sub
‘ user clicked Cancel
For Each c In rangeToSearch
If c.Value = searchValue Then
cellCount = cellCount + 1
End If
Next c
MsgBox “Number of occurrences of “ & searchValue _
& “ is “ & cellCount
End Sub

3
VBA MsgBox
The MsgBox is a dialog box in the excel VBA that can be used to inform the users of your program.

It displays a pop-up style message box and waits for the user to click a button, and then an action is
performed based on the clicked button by the user.

It provides a way for the end-users to interact with a workbook. It can be a simple alert to the users, or it can
be complicated that needs an action to proceed by the users.

Syntax

1. Msgbox (prompt, [buttons], [title], [helpfile, context])

Prompt: (required parameter) it refers to a text that is displayed as a message in the dialog box. The
maximum length of the posted message can be 1024 approximately. If the word crosses the defined range,
then the message will be divided using the carriage return character (Chr(13)) or a linefeed character
(Chr(10)) between each line.

Buttons: (optional parameter) it denotes a numeric expression to display the types of buttons, to use the
icon style, the identity of the default button, and the modality of the message box. The default value for
buttons is zero if the left side of the button is blank.

Title: (optional parameter) the title bar of the dialog box displayed the string expression. If the left side of
the dialog box is blank, then the application name is placed in the title bar.

Helpfile: A string parameter that identifies the help file to use for providing context-sensitive help for the
dialog box.

Context: The help author assigns the Help context number to an appropriate topic. If the context is
provided, then the help file must also be provided.

We can configure the message box in many ways with the help of the button parameters. That shows in the
below table, such as:

Constant Value Description

vbOKOnly 0 Display OK button only

vbOKCancel 1 Display OK and Cancel buttons

vbAbortRetryIgnore 2 Display Abort, Retry and Ignore buttons

vbYesNoCancel 3 Display Yes, No, and Cancel buttons

vbYesNo 4 Display Yes and No buttons

vbRetryCancel 5 Display Retry and Cancel buttons


vbCritical 16 Display Critical Message icon

vbQuestion 32 Display Warning Query icon

vbExclamation 48 Display Warning Message icon

VbInformation 64 Display Information Message icon

vbDefaultButton1 0 The first button is default

vbDefaultButton2 256 The second button is default

vbDefaultButton3 512 The third button is default

vbDefaultButton4 768 The fourth button is default

vbApplicationModal 0 The user must respond to the message box

vbSystemModal 4096 All applications are suspended until the user responds to
the message box

vbMsgBoxHelpButton 16384 Adds Help button to the message box

vbMsgBoxSetForeground 65536 Specifies the message box window as the foreground


window

vbMsgBoxRight 524288 Text is eight-aligned

vbMsgBoxRtlReading 1048576 Specifies text should appear as right-to-left reading on


Arabic and Hebrew systems

The above values are divided into four groups as the first group of values (0-5) describes the number and
type of buttons displayed in the dialog box. The second group of values (16, 32, 48, and 64) illustrates the
icon style. The third group of values (0, 256, and 512) determines which button is the default. And the
modality of the message box is defined in the fourth group (0, 4096). We can add only one number from
each group to create a final value for the buttons argument.

Return Values
The MsgBox function returns any one value from the following values, which is used to identify the button.
And the only thing that the user has to do that clicked in the message box.

Constant Value Description

vbOK 1 OK

vbCancel 2 Cancel

vbAbort 3 Abort
vbRetry 4 Retry

vbIgnore 5 Ignore

vbYes 6 Yes

vbNo 7 No

Examples
Suppose we want to display a message box with Yes, No, and Cancel buttons, as shown in the below code:

Executes the above function by clicking on the run button on the VBA window. It displays a "Welcome"
message box within a message box and an "OK" button.

After clicking the OK button, another dialog box is displayed with a message "do you like the red color"
and "yes", "no", and "cancel" buttons.

After clicking any button (e.g., yes), the value of that button is stored as an integer. And it displayed a pop-
up message box to the user, as shown below. Using this value, we can understand which button was clicked
by the user.
Introduction
A message box is a special dialog box used to display a piece of information to the user. As opposed to a
regular form, the user cannot type anything in the dialog box. To support message boxes, the Visual Basic
language provides a function named MsgBox. To support message boxes, the .NET Framework provides a
class named.

To display a simple message box, you can use the MsgBox() function with the following formula:

MsgBox(Message)

Inside the parentheses, pass a string. Here is an example:


Private Sub btnMessage_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnMessage.Click
MsgBox("Welcome to Microsoft Visual Basic")
End Sub

If the message is made of different sections, you can concatenate them using the & operator. You can also first declare a Str
variable, initialize it, and pass it to the function.

To create a message box using the .NET Framework, you can call the Show() method of the MessageBox class using the
following formula:

MessageBox.Show(Message)

As done for the MsgBox() function, pass a string to the method. Here is an example:

Private Sub btnMessage_Click(ByVal sender As System.Object, _


ByVal e As System.EventArgs) _
Handles btnMessage.Click
MessageBox.Show("Welcome to Microsoft Visual Basic")
End Sub

https://demoslotsgames.com/en/ showcases a vivid and colorful world where fruits and candies blend harmoniously with
rewarding bonus rounds. It's not only about fun; it's also a learning experience for those curious about the game mechanics.

In our lessons, we will mostly use the MsgBox() function, not because it is better than the MessageBox class. It is simply a
preference; but it is also because these lessons are for Microsoft Visual Basic, so we give preference to its own (rich) library

The Return Value of a Message Box

Besides displaying a message, a message box can be used to let the user make a decision by clicking a button and, dependin
the button the user would have clicked, the message box would return a value. To be able to return a value, the MsgBox()
function is declared as follows:

Public Shared Function MsgBox ( _


Prompt As Object, _
<OptionalAttribute> Optional Buttons As MsgBoxStyle = MsgBoxStyle.OkOnly, _
<OptionalAttribute> Optional Title As Object = Nothing _
) As MsgBoxResult
The value returned by a message box corresponds to a button the user would have clicked (on the message box). The return
of the MsgBox() function is based on the MsgBoxResult enumeration. The buttons and the returned values are as follows:

If the User Clicks Button Caption Integral Value


OK 1
Cancel 2
Abort 3
Retry 4
Ignore 5
Yes 6
No 7
The Buttons of a Message Box

If you create a simple message box by providing only the message, it would appear with only one button labeled OK. If you
the user to be able to make a decision and communicate it to you, provide a second argument. The second argument must be
based on the MsgBoxStyle enumeration. When it comes to buttons, some members of this enumeration are:

Integral
To Display MsgBoxStyle
Value
OKOnly 0
OKCancel 1

AbortRetryIgnore 2

YesNoCancel 3

YesNo 4

RetryCancel 5

To use any of these combinations of buttons, call the MessageBoxStyle enumeration and access the desired combination. H
an example:

Private Sub btnMessage_Click(ByVal sender As System.Object, _


ByVal e As System.EventArgs) _
Handles btnMessage.Click
MsgBox("Now we will move to the next step", MsgBoxStyle.OkCancel)
End Sub

This would produce:


The Caption of a Message Box

If you create a simple message box by providing only the message, the dialog box would appear with the name of the projec
the title. To allow you to specify a caption of your choice, provide a second string as the third argument to
the MsgBox() function. Here is an example:

Private Sub btnMessage_Click(ByVal sender As System.Object, _


ByVal e As System.EventArgs) _
Handles btnMessage.Click
MsgBox("Now we will move to the next step", _
MsgBoxStyle.OkCancel, "Lessons Objectives")
End Sub

This would produce:

The Icon of a Message Box

To enhance the appearance of a message box, you can display an icon on it. To support icons, the MsgBoxStyle enumeratio
provides the following additional members:

Integral
To Display MsgBoxStyle
Value
Critical 16

Question 32

Exclamation 48

Information 64

To apply one of these buttons, combine its style with that of the button, using the OR operator. Here is an example:

Private Sub btnMessage_Click(ByVal sender As System.Object, _


ByVal e As System.EventArgs) _
Handles btnMessage.Click
MsgBox("Are you ready to provide your credit card information?", _
MsgBoxStyle.YesNoCancel Or MsgBoxStyle.Question, _
"Customer Order Processing")
End Sub

This would produce:

The Default Button of a Message Box


When a message box is configured to display more than one button, the operating system is set to decide which button is the
default. The default button has a thick border that sets it apart from the other button(s). If the user presses Enter, the message
would behave as if the user had clicked the default button. If the message box has more than one button, you can decide wha
button would be the default. To support the default button, the MsgBoxStyle enumeration provides the following additional
options:

If the message box contains


Integral
MsgBoxStyle more than one button, the
Value
default button would be
DefaultButton1 0 the first
DefaultButton2 256 the second
DefaultButton3 512 the third

Here is an example:

Private Sub btnMessage_Click(ByVal sender As System.Object, _


ByVal e As System.EventArgs) _
Handles btnMessage.Click
MsgBox("Are you ready to provide your credit card information?", _
MsgBoxStyle.YesNoCancel Or _
MsgBoxStyle.Question Or _
MsgBoxStyle.DefaultButton2, _
"Customer Order Processing")
End Sub
VBA InputBox
VBA InputBox is used to prompt the user to enter the values. This message box is used to displaying a
message and waits for the user action performed by pressing the button.

A text can be return in the text box by using the InputBox function if the user clicks on
the OK or Enter button. And if the user clicks on the Cancel button, then the InputBox function will return an
empty string (" ").

InputBox function needs proper error handling. If the user clicks the cancel button without entering any
value, then it displayed an error.

Syntax

1. InputBox(prompt[,title][,default][,xpos][,ypos][,helpfile,context])
o Prompt (required parameter): This parameter represents a string, and it is used to display as a
message in the dialog box. The minimum length of prompt is 1024 characters approximately. If the
length of the text is increased, then break the text by using a linefeed character (Chr(10)) or carriage
return character (Chr(13)) between each line of the text.
o Title (optional parameter): The title is a string expression. It is used to display the string in the title bar
of the dialog box. And the application name is placed in the title bar if the left side of the title is
empty.
o Default (optional parameter): It takes the text as a default parameter in the textbox to display it to the
users.
o XPos (optional parameter): The position of the X-axis is used to show the prompt distance from the
left side of the screen as horizontally. The input box is centered horizontally if its value is null.
o YPos (optional parameter): The position of the Y-axis is used to show the prompt distance from the
left side of the screen as vertically. , then the input box is centered vertically If its value is blank.
o Helpfile (optional parameter): The helpfile is a string expression. This parameter is used to identify the
help file that provides context-sensitive help to the dialog box.
o Context (optional parameter): It is a numeric expression that is used to identify the Help context
number. This number is assigned to a suitable help topic by the Help author. The helpfile must be
present if we want to provide the context.

How to Create InputBox


To create the InputBox in VBA, follow the below steps, such as:

Step 1: Go to the Visual Basic Editor and insert a new module.


Step 2: Double click on the recently added module and write the macro name, i.e., InputBox_Example.

Step 3: Write the word "InputBox", and we will see the syntax of the InputBox.

Step 4: Now give the Prompt as "Your Name", title as "personal information", and Default as "Enter Here".

Step 5: Run the code using the Run button.


InputBox Type Parameter Options

Number Type of Value

0 Only Formula can be entered.

1 The only number can be entered.

2 Only text can be entered.

4 Only Logical value (True or False) can be entered.

8 Only select the cell reference.

16 Only error values entered.

64 An array of the values.

Example
We use the popular features of an InputBox function shown in the following example, such as:

o This code asks for the input with the help of an InputBox and assigns it to a variable.
o It verifies the code; otherwise, it exists.

Now run the above code using the Run button, and we will get the result in a message box, such as:
While the dialog box is displayed, then the user has to press one of the buttons.

When the user presses any one button from the displayed buttons, then a text string is return with the help
of the InputBox function.

o If the user clicks on the OK button, then the text string has been entered into the dialog box.
o If the user clicks on the Cancel button, then an empty text string is returned.

In the above example, the returned text string is assigned to the MyInput variable before the execution of
the code.
VB.Net - PrintDialog Control
The PrintDialog control lets the user to print documents by selecting a printer and choosing which
sections of the document to print from a Windows Forms application.

There are various other controls related to printing of documents. Let us have a brief look at these
controls and their purpose. These other controls are −

 The PrintDocument control − it provides support for actual events and operations of
printing in Visual Basic and sets the properties for printing.
 The PrinterSettings control − it is used to configure how a document is printed by specifying
the printer.
 The PageSetUpDialog control − it allows the user to specify page-related print settings
including page orientation, paper size and margin size.
 The PrintPreviewControl control − it represents the raw preview part of print previewing
from a Windows Forms application, without any dialog boxes or buttons.
 The PrintPreviewDialog control − it represents a dialog box form that contains a
PrintPreviewControl for printing from a Windows Forms application.

Following is the Print dialog box −

Properties of the PrintDialog Control


The following are some of the commonly used properties of the PrintDialog control −
Sr.No. Property & Description

AllowCurrentPage
1 Gets or sets a value indicating whether the Current
Page option button is displayed.

AllowPrintToFile
2 Gets or sets a value indicating whether the Print to file check
box is enabled.

AllowSelection
3 Gets or sets a value indicating whether the Selection option
button is enabled.

AllowSomePages
4 Gets or sets a value indicating whether the Pages option
button is enabled.

Document
5 Gets or sets a value indicating the PrintDocument used to
obtain PrinterSettings.

PrinterSettings
6
Gets or sets the printer settings the dialog box modifies.

PrintToFile
7 Gets or sets a value indicating whether the Print to file check
box is selected.

ShowHelp
8 Gets or sets a value indicating whether the Help button is
displayed.

ShowNetwork
9 Gets or sets a value indicating whether the Network button
is displayed.

Methods of the PrintDialog Control


The following are some of the commonly used methods of the PrintDialog control −

Sr.No. Method Name & Description

Reset
1
Resets all options to their default values.

RunDialog
2 When overridden in a derived class, specifies a common
dialog box.

ShowDialog
3
Runs a common dialog box with a default owner.
Example
In this example, let us see how to show a Print dialog box in a form. Take the following steps −

 Add a PrintDocument control, a PrintDialog control and a Button control on the form. The
PrintDocument and the PrintDialog controls are found on the Print category of the controls
toolbox.
 Change the text of the button to 'Print'.
 Double-click the Print button and modify the code of the Click event as shown −
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
PrintDialog1.Document = PrintDocument1
PrintDialog1.PrinterSettings = PrintDocument1.PrinterSettings
PrintDialog1.AllowSomePages = True

If PrintDialog1.ShowDialog = DialogResult.OK Then


PrintDocument1.PrinterSettings = PrintDialog1.PrinterSettings
PrintDocument1.Print()
End If
End Sub

When the application is compiled and run using Start button available at the Microsoft Visual
Studio tool bar, it will show the following window −

Click the Print button to make the Print dialog box appear.
Visual Basic If Statement
In Visual Basic, If statement is useful to execute the block of code or statements conditionally based on the value of an
expression.

Generally, in Visual Basic, the statement that needs to be executed based on the condition is known as a “Conditional
Statement” and the statement is more likely a block of code.

Syntax of Visual Basic if Statement


Following is the syntax of defining the if statement in Visual Basic programming language.

If bool_expression Then
// Statements to Execute if condition is true
End If
If you observe the above If statement syntax, the statements inside of the If condition will be executed only when the
“bool_expression” returns true otherwise, those statements will be ignored for execution.

Following is the sample example of using the If statement in Visual Basic programming language.

Dim x As Integer = 20
If x >= 10 Then
Console.WriteLine("Number Greater than 10")
End If
If you observe the above example, the Console statement will be executed only when the defined condition (x >= 10)
returns true.

Visual Basic If Statement Flow Chart Diagram


Following is the flow chart diagram, which will represent the process flow of the If statement in Visual Basic
programming language.

If you observe the above Visual Basic If statement flow chart diagram, when the defined condition is true, the
statements within the If condition will be executed; otherwise, the If condition will end without executing the
statements.
Visual Basic If Statement Example
Following is the example of defining the If statement in Visual Basic programming language to execute the block of
code or statements based on a Boolean expression.

Module Module1
Sub Main()
Dim x As Integer = 20, y As Integer = 10
If x >= 10 Then
Console.WriteLine("x is Greater than 10")
End If
If y <= 5 Then
Console.WriteLine("y is less than or equals to 5")
End If
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module
If you observe the above example, we defined two If conditions to execute the statements based on the defined
variables (x, y) values.

When we execute the above Visual Basic program, we will get the result as shown below.

If you observe the above result, only one If condition is true that’s the reason only one statement printed on the
console window.

This is how we can use the If statement in Visual Basic programming language to execute the block of code or
statements based on our requirements.
VB.Net - Looping Statements
There may be a situation when you need to execute a block of code several number of times. In
general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on.

Programming languages provide various control structures that allow for more complicated
execution paths.

A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages −

VB.Net provides following types of loops to handle looping requirements. Click the following links
to check their details.

Loop Type Description


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.
For...Next 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.
For Each...Next 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.
While... End While It executes a series of statements as long as a
given condition is True.
With... End With It is not exactly a looping construct. It executes a
series of statements that repeatedly refer to a
single object or structure.
Nested loops You can use one or more loops inside any another
While, For or Do loop.

Loop Control Statements


Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.

VB.Net provides the following control statements. Click the following links to check their details.

Control Statement Description


Exit statement Terminates the loop or select case statement
and transfers execution to the statement
immediately following the loop or select case.
Continue statement Causes the loop to skip the remainder of its body
and immediately retest its condition prior to
reiterating.
GoTo statement Transfers control to the labeled statement.
Though it is not advised to use GoTo statement in
your program.
VB.NET Exit Statement
In VB.NET, the Exit statement is used to terminate the loop (for, while, do, select case, etc.) or exit the
loop and pass control immediately to the next statement of the termination loop. Furthermore, the Exit
statement can also be used in the nested loop to stop or terminate the execution of the inner or outer loop
at any time, depending on our requirements.

Syntax

1. Exit { Do | For | Function | Property | Select | Sub | Try | While }

The flow of Exit Statement


Following is the diagrammatical representation of Exit Statement in VB.NET programming language.

Generally, the Exit statement is written along with a condition. If the Exit condition is true inside the loop, it
exits from the loop and control transfer to the next statement, followed by the loop. And if
the Exit condition fails for the first time, it will not check any statement inside the loop and terminates the
program.

We will now see how to use the Exit statement in loops and Select case statements to finish the program's
execution in the VB.NET programming language.

Use of Exit statement in While End loop


Example 1: Write a simple program to use the Exit Statement in While End loop.

Exit_While.vb

Imports System
Module Exit_While
Sub Main()
' Definition of count variable
Dim count As Integer = 1

' Execution of While loop


While (count < 10)
' Define the Exit condition using If statement
If count = 5 Then
Exit While ' terminate the While loop
End If
Console.WriteLine(" Value of Count is : {0}", count)
count = count + 1
End While
Console.WriteLine(" Exit from the While loop when count = {0}", count)
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Module

Output:

In the above example, the While End loop is continuously executed, its body until the given condition While
(count < 10) is not satisfied. But when the Exit condition (count = 5) falls inside a while loop, the execution
of the loop is automatically terminated, and control moves to the next part of the loop statement.

Use of Exit statement in For Next loop


Example 2: Write a program to calculate the sum of 10 numbers, and if a negative number is entered,
the For Each loop ends.

Imports System
Module Exit_For
Sub Main()
'Definition of num variable
Dim num As Integer
Dim sum As Double = 0.0
'Execution of For loop
For i As Integer = 1 To 10
'Accept a number from the user
Console.WriteLine("Enter a number : ")
num = Console.ReadLine()
' If the user enters a negative number, the loop terminates
If num < 0 Then
Exit For ' terminate the For loop
End If
sum += num
Next

Console.WriteLine(" Exit from the For loop when (num < 0) is: {0}", num)
Console.WriteLine(" Total sum is : {0}", sum)
Console.WriteLine(" Press any key to exit from the Console Screen")
Console.ReadKey()
End Sub
End Module

Output:

The above program accepts a number from the user until it encounters a negative or less than 0 (num < 0).
And when there is a negative number, the Exit statement terminates the loop, and the control transfer to the
next part of the loop.

Use of Exit statement in Do While loop


Example 3: Write a simple program to use the Exit Statement in Do While Loop.

Exit_Do_While.vb

Imports System
Module Exit_Do_While
Sub Main()
'Definition of the count variable
Dim count As Integer = 20

' Definition of Do While loop


Do
'Define the Exit condition using If statement.

If count = 25 Then
Exit Do ' terminate the Do While loop
End If
Console.WriteLine(" Value of Count is : {0}", count)
count = count + 1
Loop While (count < 50)
Console.WriteLine(" Exit from the Do While loop when count = {0}", count)
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Module

Output:

In the above example, the Do While loop is continuously executed, its body until the given condition While
(count < 50) is not satisfied. But when the Exit condition (count = 25) is encountered, the Do While loop is
automatically terminated. The control is immediately transferred to the next statement, followed by the loop
statements.
Visual Basic Exit Statement
In visual basic, the Exit statement is useful to terminate the execution of loops (for, while, do-while, etc.) and transfers
the control immediately to the next statements that follow a terminated loops or statements.

In visual basic, we can also use Exit statement in nested loops to stop or terminate the execution of inner loops based
on our requirements.

Visual Basic Exit Statement


Following is the syntax of defining the Exit statement in a visual basic programming language.

Exit { Do | For | Function | Property | Select | Sub | Try | While }


In our applications, we can use Exit statement with Do, For, Function, Property, etc. to stop or terminate the execution
of a particular loop or statement based on our requirements.

Visual Basic Break Statement Flow Chart


Following is the pictorial representation of Exit statement process flow in a visual basic programming language.

Now, we will see how to use Exit statement in for loop, while loop, do-while loop to terminate the execution of loops
in a visual basic programming language with examples.

Visual Basic For Loop with Exit Statement


In visual basic, by using Exit keyword, we can stop the execution of for loop statement based on our requirements.

Following is the example of terminating the execution of for loop with Exit statement.
Module Module1
Sub Main()
For i As Integer = 1 To 4
If i = 3 Then Exit For
Console.WriteLine("i value: {0}", i)
Next
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module
If you observe the above code, we used the Exit statement to terminate the for loop whenever the variable i value
equals 3.

When we execute the above visual basic program, we will get the result as shown below.

If you observe the above result, whenever the variable i value equals 3, the for loop execution automatically stops.

This is how we can use the Exit statement in for loop to terminate the execution of for loop based on our
requirements.

Visual Basic While Loop with Exit Statement


In visual basic, we can exit or terminate the execution of the while loop immediately by using Exit keyword.

Following is the example of using Exit keyword in a while loop to terminate loop execution in a visual basic
programming language.

Module Module1
Sub Main()
Dim i As Integer = 1
While i < 4
Console.WriteLine("i value: {0}", i)
i += 1
If i = 2 Then Exit While
End While
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module
If you observe the above example, whenever the variable (i) value become 2, we are terminating the while
loop using Exit statement.

When we execute the above visual basic program, we will get the result as shown below.
This is how we can use the Exit statement with the while loop to terminate the execution of the loop based on our
requirements.

Visual Basic Do-While Loop with Exit Statement


In visual basic, we can exit or terminate the execution of the do-while loop immediately by using Exit keyword.

Following is the example of using Exit keyword in a do-while loop to terminate loop execution in a visual basic
programming language.

Module Module1
Sub Main()
Dim i As Integer = 1
Do
Console.WriteLine("i value: {0}", i)
i += 1
If i = 2 Then Exit Do
Loop While i < 4
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module
If you observe the above example, whenever the variable (i) value become 2, we are terminating the loop
using Exit statement.

We will get the following result when we execute the above visual basic program.

This is how we can use the Exit statement in the do-while loop to terminate the execution of the loop based on our
requirements.

This is how we can use the Exit statement in our visual basic applications to terminate the execution of loops or
statements based on our requirements.
Nested Control Structures VB Help
You can place, or nest, control structures inside other control structures (such as an If… Then
block within a For … Next loop). Control structures in Visual Basic can be nested in as many
levels as you want. It’s common practice to indent the bodies of nested decision and loop
structures to make the program easier to read. Here is the structure of a nested For … Next loop
that scans all the elements” of a two-dimensional array:

The outer loop (with the irow counter) scans each row of the array, and the inner loop scans
each column. The outer loop scans each element in the first row of-the array, the elements of the
second row, and so on, until the entire array has been scanned. The loop’s body can process the
element Array2/irow, icol).
You can also nest control flow structures. The following structure tests a user supplied value to
determine if it’s positive and, if so, determines whether the value exceeds a certain limit:

The Income variable is first compared with zero. If it’s negative, the Else clause of the U… Then
statement is executed-If it’s positive, it’s compared with the value 20000, and depending on the
outcome, a different message is displayed.
The Exit Statement
The Exit statement allows you to exit prematurely from a block of statements in a control
structure, from a loop, or even from a procedure. Suppose you have a For … Next loop that
calculates the square root of a ~es of numbers. Because the square root of negative numbers
can’t be calculated (the Sqr() function generates a runtime error), you might want to.halt the
operation if the array contains an invalid value. To exit the loop prematurely, use the Exit For
statement as follows:

If a negative element is found in this loop, the program exits.the loop and continues with the
statement following the Next statement.
There are similar Exit statements for the Do loop (Exit Do), as well as for functions and
subroutines (Exit Function and Exit Subroutine). If the previous loop was part of a function, you
might want to assign an error code to the function and exit not only the loop” but the function
itself:
If this code is part of a subroutine procedure, you use the Exit Subroutine statement. The
Exit statements for loops are Exit For and Exit Do. There is no way (or compelling reason) to exit
prematurely from an If or Case statement. There is also an Exit Property statement, which we’ll
look at in Chapter 16, Building Active Controls .
Nested Control Structures
You can place, or nest, control structures inside other control structures (such as an If. . .Then block
within a For. . .Next loop). Control structures in Visual Basic can be nested in as many levels as you
want. The editor automatically indents the bodies of nested decision and loop structures to make the
program easier to read.

When you nest control structures, you must make sure that they open and close within the same
structure. In other words, you can’t start a For. . .Next loop in an If statement and close the loop
after the corresponding End If. The following code segment demonstrates how to nest several flow-
control statements. (The curly brackets denote that regular statements should appear in their place
and will not compile, of course.)

For a = 1 To 100
{ statements }
If a = 99 Then
{ statements }
End If
While b < a
{ statements }
If total <= 0 Then
{ statements }
End If
End While
For c = 1 to a
{ statements }
Next c
Next aCode language: VB.NET (vbnet)
I’m showing the names of the counter variables after the Next statements to make the code more
readable. To find the matching closing statement (Next, End If, or End While), move down from the
opening statement until you hit a line that starts at the same column. This is the matching closing
statement. Notice that you don’t have to align the nested structures yourself; the editor reformats the
code automatically as you edit. It also inserts the matching closing statement— the End If statement
is inserted automatically as soon as you enter an If statement, for example.

Listing 3.6 shows the structure of a nested For. . .Next loop that scans all the elements of a two-
dimensional array.

Listing 3.6: Iterating through a Two-Dimensional Array

Dim Array2D(6, 4) As Integer


Dim iRow, iCol As Integer
For iRow = 0 To Array2D.GetUpperBound(0)
For iCol = 0 To Array2D.GetUpperBound(1)
Array2D(iRow, iCol) = iRow * 100 + iCol
Debug.Write(iRow & ", " & iCol & " = " & _
Array2D(iRow, iCol) & " ")
Next iCol
Debug.WriteLine()
Next iRowCode language: VB.NET (vbnet)
The outer loop (with the iRow counter) scans each row of the array. At each iteration, the inner loop
scans all the elements in the row specified by the counter of the outer loop (iRow). After the inner
loop completes, the counter of the outer loop is increased by one, and the inner loop is executed
again — this time to scan the elements of the next row. The loop’s body consists of two statements
that assign a value to the current array element and then print it in the Output window. The current
element at each iteration is Array2D(iRow, iCol).

You can also nest multiple If statements. The code in Listing 3.7 tests a user-supplied value to
determine whether it’s positive; if so, it determines whether the value exceeds a certain limit.

Listing 3.7: Simple Nested If Statements

Dim Income As Decimal


Income = Convert.ToDecimal(InputBox("Enter your income"))
If Income > 0 Then
If Income > 12000 Then
MsgBox "You will pay taxes this year"
Else
MsgBox "You won't pay any taxes this year"
End If
Else
MsgBox "Bummer"
End IfCode language: VB.NET (vbnet)
The Income variable is first compared with zero. If it’s negative, the Else clause of the If. . .Then
statement is executed. If it’s positive, it’s compared with the value 12,000, and depending on the
outcome, a different message is displayed. The code segment shown here doesn’t perform any
extensive validations and assumes that the user won’t enter a string when prompted for her income.

The Exit Statement


The Exit statement allows you to exit prematurely from a block of statements in a control structure,
from a loop, or even from a procedure. Suppose that you have a For. . .Next loop that calculates the
square root of a series of numbers. Because the square root of negative numbers can’t be
calculated (the Math.Sqrt method will generate a runtime error), you might want to halt the operation
if the array contains an invalid value. To exit the loop prematurely, use the Exit For statement as
follows:

For i = 0 To UBound(nArray)
If nArray(i) < 0 Then
MsgBox("Can't complete calculations" & vbCrLf & _
"Item " & i.ToString & " is negative! "
Exit For
End If
nArray(i) = Math.Sqrt(nArray(i))
NextCode language: VB.NET (vbnet)
If a negative element is found in this loop, the program exits the loop and continues with the
statement following the Next statement.
There are similar Exit statements for the Do loop (Exit Do), the While loop (Exit While), the Select
statement (Exit Select), and for functions and subroutines (Exit Function and Exit Sub). If the
previous loop was part of a function, you might want to display an error and exit not only the loop,
but also the function itself by using the Exit Function statement.
VB.NET Arrays
An array is a linear data structure that is a collection of data elements of the same type stored on
a contiguous memory location. Each data item is called an element of the array. It is a fixed size of
sequentially arranged elements in computer memory with the first element being at index 0 and the last
element at index n - 1, where n represents the total number of elements in the array.

The following is an illustrated representation of similar data type elements defined in the VB.NET array data
structure.

In the above diagram, we store the Integer type data elements in an array starting at index 0. It will continue
to store data elements up to a defined number of elements.

Declaration of VB.NET Array


We can declare an array by specifying the data of the elements followed by parentheses () in the VB.NET.

1. Dim array_name As [Data_Type] ()

In the above declaration, array_name is the name of an array, and the Data_Type represents the type of
element (Integer, char, String, Decimal) that will to store contiguous data elements in the VB.NET array.

Now, let us see the example to declare an array.

1. 'Store only Integer values


2. Dim num As Integer() or Dim num(5) As Integer
3. 'Store only String values
4. Dim name As String() or Dim name(5) As String
5. ' Store only Double values
6. Dim marks As Double()

Initialization of VB.NET Array


In VB.NET, we can initialize an array with New keyword at the time of declaration. For example,

1. 'Declaration and Initialization of an array elements with size 6


2. Dim num As Integer() = New Integer(5) { }
3. Dim num As Integer() = New Integer(5) {1, 2, 3, 4, 5, 6}
4. Initialize an array with 5 elements that indicates the size of an array
5. Dim arr_name As Integer() = New Integer() {5, 10, 5, 20, 15}
6. Declare an array
7. Dim array1 As Char()
8. array1 = New Char() {'A', 'B', 'C', 'D', 'E'}

Furthermore, we can also initialize and declare an array using the following ways, as shown below.

1. Dim intData() As Integer = {1, 2, 3, 4, 5}


2. Dim intData(5) As Integer
3. Dim array_name() As String = {"Peter", "John", "Brock", "James", "Maria"}
4. Dim misc() as Object = {"Hello friends", 16c, 12ui, "A"c}
5. Dim Emp(0 to 2) As String
6. Emp{0} = "Mathew"
7. Emp(1) = " Anthony"
8. Emp(2) = "Prince"

Let's create a program to add the elements of an array in VB.NET programming language.

num_Array.vb

1. Imports System
2. Module num_Array
3. Sub Main()
4. Dim i As Integer, Sum As Integer = 0
5. 'In VB.NET the size of an array is n+1
6. 'Declaration and Initialization of marks() array
7. Dim marks() As Integer = {58, 68, 95, 50, 23, 89}
8. Console.WriteLine(" Marks in 6 Subjects")
9. For i = 0 To marks.Length - 1
10. Console.WriteLine(" Marks {0}", marks(i))
11. Sum = Sum + marks(i)
12. Next
13. Console.WriteLine(" Grand total is {0}", Sum)
14.
15. Console.WriteLine(" Press any key to exit...")
16. Console.ReadKey()
17. End Sub
18. End Module

Output:
In the above program, we create an integer array with name marks() and define a For loop to access each
item of the array marks.

Input number in VB.NET Array


Let's create a program to take input values from the user and display them in VB.NET programming
language.

Input_array.vb

1. Imports System
2. Module Input_array
3. Sub Main()
4. 'Definition of array
5. Dim arr As Integer() = New Integer(5) {}
6. For i As Integer = 0 To 5
7. Console.WriteLine(" Enter the value for arr[{0}] : ", i)
8. arr(i) = Console.ReadLine() ' Accept the number in array
9. Next
10. Console.WriteLine(" The array elements are : ")
11. ' Definition of For loop
12. For j As Integer = 0 To 5
13.
14. Console.WriteLine("{0}", arr(j))
15. Next
16.
17. Console.WriteLine(" Press any key to exit...")
18. Console.ReadKey()
19. End Sub
20. End Module

Output:
Multidimensional Array
In VB.NET, a multidimensional array is useful for storing more than one dimension in a tabular form, such as
rows and columns. The multidimensional array support two or three dimensional in VB.NET.

Declaration of Multidimensional Array

1. Declaration of two-dimensional array


2. Dim twoDimenArray As Integer( , ) = New Integer(3, 2) {}
3. Or Dim arr(5, 3) As Integer
4. Representation of Three Dimensional array
5. Dim arrThree(2, 4, 3) As Integer
6. Or Dim arr1 As Integer( , , ) = New Integer(5, 5, 5) { }

In the above representation of multidimensional, we have created 2-dimensional array twoDimenArray


with 3 rows and 2 columns and 3-dimensional array with three dimensions 2, 4, and 3.

Initialization of Multidimensional Array

The following ways to initialize the multidimensional array:

1. ' Initialization of Two Dimensional Array


2. Dim intArray As Integer( , ) = New Integer( 3, 2) { {4, 5}, {2, 3}, {6, 7} }
3. Dim intArray( , ) As Integer = { {5, 4}, {3, 2}, {4, 7} }
4. ' Initialization of Three Dimensional Array
5. Dim threeDimen(3, 3, 2 ) As Integer = { {{1, 3, 2}, {2, 3, 4}}, {{5, 3, 6}, {3, 4, 5}}, {{1, 2, 2}, {5, 2, 3} }}

Multidimensional Array Example

Let's create a program to understand the multidimensional array.

MultidimenArray.vb
1. Imports System
2. Module MultidimenArray
3. Sub Main()
4. ' Definition of 2 Dimensional Array
5. Dim intArray(,) As Integer = {{5, 4}, {3, 2}, {4, 7}, {4, 5}}
6.
7. ' Definition of 3 Dimensional Array
8. Dim threeDimen(,,) As Integer =
9. {{{1, 3, 2}, {2, 3, 4}},
10. {{5, 3, 6}, {3, 4, 5}},
11. {{1, 2, 2}, {5, 2, 3}}}
12.
13. Console.WriteLine(" Two Dimensional Arraye in VB.NET are")
14. For i As Integer = 0 To 3
15. For j As Integer = 0 To 1
16. Console.WriteLine("intArray[{0}, {1}] = {2}", i, j, intArray(i, j))
17. Next j
18. Next i
19.
20. Console.WriteLine(" Three Dimensional Arraye in VB.NET are")
21. For i As Integer = 0 To 2 - 1
22. For j As Integer = 0 To 2 - 1
23. For k As Integer = 0 To 4
24. Console.WriteLine("intArray[{0}, {1}, {2}] = {3}", i, j, k, threeDimen(i, j, k))
25. Next k
26. Next j
27. Next i
28.
29. Console.WriteLine(" Press any key to exit...")
30. Console.ReadKey()
31. End Sub
32. End Module

Output:
Fixed Size Array
In VB.NET, a fixed- size array is used to hold a fixed number of elements in memory. It means that we have
defined the number of elements in the array declaration that will remain the same during the definition of
the elements, and its size cannot be changed. For example, we need to hold only 5 names in an array; it can
be defined and initialized in the array such as,

1. Dim names( 0 to 4) As String


2. names(0) = "Robert"
3. names(1) = "Henry"
4. names(2) = "Rock"
5. names(3) = "James"
6. names(4) = "John"

The above representation of the fixed array is that we have defined a string array names 0 to 4, which stores
all the elements in the array from 0 to index 4.
VB.Net - 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.

Creating Arrays in VB.Net


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}

The elements in an array can be stored and accessed by using the index of the
array. The following program demonstrates this −

Live Demo
Module arrayApl
Sub Main()
Dim n(10) As Integer ' n is an array of 11 integers '
Dim i, j As Integer
' initialize elements of array n '

For i = 0 To 10
n(i) = i + 100 ' set element at location i to i + 100
Next i
' output each array element's value '

For j = 0 To 10
Console.WriteLine("Element({0}) = {1}", j, n(j))
Next j
Console.ReadKey()
End Sub
End Module

When the above code is compiled and executed, it produces the following result −

Element(0) = 100
Element(1) = 101
Element(2) = 102
Element(3) = 103
Element(4) = 104
Element(5) = 105
Element(6) = 106
Element(7) = 107
Element(8) = 108
Element(9) = 109
Element(10) = 110

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 ReDim statement.

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.
Module arrayApl
Sub Main()
Dim marks() As Integer
ReDim marks(2)
marks(0) = 85
marks(1) = 75
marks(2) = 90

ReDim Preserve marks(10)


marks(3) = 80
marks(4) = 76
marks(5) = 92
marks(6) = 99
marks(7) = 79
marks(8) = 75

For i = 0 To 10
Console.WriteLine(i & vbTab & marks(i))
Next i
Console.ReadKey()
End Sub
End Module

When the above code is compiled and executed, it produces the following result −

0 85
1 75
2 90
3 80
4 76
5 92
6 99
7 79
8 75
9 0
10 0

Multi-Dimensional Arrays
VB.Net allows multidimensional arrays. Multidimensional arrays are also called
rectangular arrays.

You can declare a 2-dimensional array of strings as −

Dim twoDStringArray(10, 20) As String

or, a 3-dimensional array of Integer variables −

Dim threeDIntArray(10, 10, 10) As Integer

The following program demonstrates creating and using a 2-dimensional array −

Live Demo
Module arrayApl
Sub Main()
' an array with 5 rows and 2 columns
Dim a(,) As Integer = {{0, 0}, {1, 2}, {2, 4}, {3, 6}, {4, 8}}
Dim i, j As Integer
' output each array element's value '

For i = 0 To 4
For j = 0 To 1
Console.WriteLine("a[{0},{1}] = {2}", i, j, a(i, j))
Next j
Next i
Console.ReadKey()
End Sub
End Module

When the above code is compiled and executed, it produces the following result −

a[0,0]: 0
a[0,1]: 0
a[1,0]: 1
a[1,1]: 2
a[2,0]: 2
a[2,1]: 4
a[3,0]: 3
a[3,1]: 6
a[4,0]: 4
a[4,1]: 8

Jagged Array
A Jagged array is an array of arrays. The following code shows declaring a jagged
array named scores of Integers −

Dim scores As Integer()() = New Integer(5)(){}

The following example illustrates using a jagged array −

Live Demo
Module arrayApl
Sub Main()
'a jagged array of 5 array of integers
Dim a As Integer()() = New Integer(4)() {}
a(0) = New Integer() {0, 0}
a(1) = New Integer() {1, 2}
a(2) = New Integer() {2, 4}
a(3) = New Integer() {3, 6}
a(4) = New Integer() {4, 8}
Dim i, j As Integer
' output each array element's value
For i = 0 To 4
For j = 0 To 1
Console.WriteLine("a[{0},{1}] = {2}", i, j, a(i)(j))
Next j
Next i
Console.ReadKey()
End Sub
End Module

When the above code is compiled and executed, it produces the following result −

a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8

The Array Class


The Array class is the base class for all the arrays in VB.Net. It is defined in the
System namespace. The Array class provides various properties and methods to
work with arrays.

Properties of the Array Class

The following table provides some of the most commonly used properties of
the Array class −

Sr.No Property Name & Description

IsFixedSize
1
Gets a value indicating whether the Array has a fixed size.

IsReadOnly
2
Gets a value indicating whether the Array is read-only.

Length
3 Gets a 32-bit integer that represents the total number of elements
in all the dimensions of the Array.

LongLength
4 Gets a 64-bit integer that represents the total number of elements
in all the dimensions of the Array.
Rank
5
Gets the rank (number of dimensions) of the Array.

Methods of the Array Class

The following table provides some of the most commonly used methods of
the Array class −

Sr.No Method Name & Description

Public Shared Sub Clear (array As Array, index As Integer,


length As Integer)
1
Sets a range of elements in the Array to zero, to false, or to null,
depending on the element type.

Public Shared Sub Copy (sourceArray As Array,


destinationArray As Array, length As Integer)
2 Copies a range of elements from an Array starting at the first
element and pastes them into another Array starting at the first
element. The length is specified as a 32-bit integer.

Public Sub CopyTo (array As Array, index As Integer)


Copies all the elements of the current one-dimensional Array to
3
the specified one-dimensional Array starting at the specified
destination Array index. The index is specified as a 32-bit integer.

Public Function GetLength (dimension As Integer) As Integer


4 Gets a 32-bit integer that represents the number of elements in the
specified dimension of the Array.

Public Function GetLongLength (dimension As Integer) As


Long
5
Gets a 64-bit integer that represents the number of elements in the
specified dimension of the Array.

Public Function GetLowerBound (dimension As Integer) As


6 Integer
Gets the lower bound of the specified dimension in the Array.

Public Function GetType As Type


7
Gets the Type of the current instance (Inherited from Object).

Public Function GetUpperBound (dimension As Integer) As


8 Integer
Gets the upper bound of the specified dimension in the Array.

Public Function GetValue (index As Integer) As Object


9 Gets the value at the specified position in the one-dimensional
Array. The index is specified as a 32-bit integer.

Public Shared Function IndexOf (array As Array,value As


10 Object) As Integer
Searches for the specified object and returns the index of the first
occurrence within the entire one-dimensional Array.

Public Shared Sub Reverse (array As Array)


11 Reverses the sequence of the elements in the entire one-
dimensional Array.

Public Sub SetValue (value As Object, index As Integer)


12 Sets a value to the element at the specified position in the one-
dimensional Array. The index is specified as a 32-bit integer.

Public Shared Sub Sort (array As Array)


13 Sorts the elements in an entire one-dimensional Array using the
IComparable implementation of each element of the Array.

Public Overridable Function ToString As String


14 Returns a string that represents the current object (Inherited from
Object).

For complete list of Array class properties and methods, please consult Microsoft
documentation.

Example

The following program demonstrates use of some of the methods of the Array class:

Live Demo
Module arrayApl
Sub Main()
Dim list As Integer() = {34, 72, 13, 44, 25, 30, 10}
Dim temp As Integer() = list
Dim i As Integer
Console.Write("Original Array: ")

For Each i In list


Console.Write("{0} ", i)
Next i
Console.WriteLine()
' reverse the array
Array.Reverse(temp)
Console.Write("Reversed Array: ")

For Each i In temp


Console.Write("{0} ", i)
Next i
Console.WriteLine()
'sort the array
Array.Sort(list)
Console.Write("Sorted Array: ")

For Each i In list


Console.Write("{0} ", i)
Next i
Console.WriteLine()
Console.ReadKey()
End Sub
End Module

When the above code is compiled and executed, it produces the following result −

Original Array: 34 72 13 44 25 30 10
Reversed Array: 10 30 25 44 13 72 34
Sorted Array: 10 13 25 30 34 44 72
VB.NET Dynamic Array
A Dynamic array is used when we do not know how many items or elements to be inserted in an array. To
resolve this problem, we use the dynamic array. It allows us to insert or store the number of elements at
runtime in sequentially manner. A Dynamic Array can be resized according to the program's requirements at
run time using the "ReDim" statement.

Initial Declaration of Array


Syntax:

1. Dim array_name() As Integer

Runtime Declaration of the VB.NET Dynamic array (Resizing)


Syntax:

1. ReDim {Preserve] array_name(subscripts)

The ReDim statement is used to declare a dynamic array. To resize an array, we have used
a Preserve keyword that preserve the existing item in the array. The array_name represents the name of the
array to be re-dimensioned. A subscript represents the new dimension of the array.

Initialization of Dynamic Array

1. Dim myArr() As String


2. ReDim myArr(3)
3. myArr(0) = "One"
4. myArr(1) = "Two"
5. myArr(2) = "Three"
6. myArr(3) = "Four"

To initialize a Dynamic Array, we have used create a string array named myArr() that uses the Dim statement
in which we do not know the array's actual size. The ReDim statement is used to resize the existing array by
defining the subscript (3). If we want to store one more element in index 4 while preserving three elements
in an array, use the following statements.

ReDim Preserve myArr(4)


myArr(4) = "Five"

the above array has four elements.

Also, if we want to store multiple data types in an array, we have to use a Variant data type.

Dim myArr() As Variant


ReDim myArr(3)
myArr(0) = 10
myArr(0) = "String"
myArr(0) = false
myArr(0) = 4.6

Let's create a program to understand the dynamic array.

Dynamic_Arr.vb

Imports System
Module Dynamic_Arr
Sub Main()
'Declaration and Initialization of String Array Days()
Dim Days(20) As String
' Resize an Array using the ReDim Statement
ReDim Days(6)
Days(0) = "Sunday"
Days(1) = "Monday"
Days(2) = "Tuesday"
Days(3) = "Wednesday"
Days(4) = "Thursday"
Days(5) = "Friday"
Days(6) = "Saturday"

For i As Integer = 0 To Days.Length - 1


Console.WriteLine("Days Name in [{0}] index is {1}", i, Days(i))
Next
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Module

Output:
Adding New Element to an Array
When we want to insert some new elements into an array of fixed size that is already filled with old array
elements. So, in this case, we can use a dynamic array to add new elements to the existing array.

Let us create a program to understand how we can add new elements to a dynamic array.

Dynamic_Arr1.vb

Imports System
Module Dynamic_arr1
Sub Main()
'Declaration and Initialization of String Array Days()
Dim Days() As String
' Resize an Array using the ReDim Statement
ReDim Days(2)
Days(0) = "Sunday"
Days(1) = "Monday"
Days(2) = "Tuesday"
Console.WriteLine(" Before Preserving the Elements")
For i As Integer = 0 To Days.Length - 1
Console.WriteLine("Days Name in [{0}] index is {1}", i, Days(i))
Next
Console.WriteLine()

Console.WriteLine(" After Preserving 0 to 2 index Elements")


ReDim Preserve Days(6)
Days(3) = "Wednesday"
Days(4) = "Thursday"
Days(5) = "Friday"
Days(6) = "Saturday"
For i As Integer = 0 To Days.Length - 1
Console.WriteLine("Days Name in [{0}] index is {1}", i, Days(i))
Next
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Module

Output:
In the above program, we have created a dynamic array Days as a String that executes the first three
elements of Days such as Sunday, Monday, and Tuesday. we have also used a Preserve Keyword to keep
the existing elements of an array with new elements in dynamic array Days.
Subroutines and Functions
The code you write won’t be a monolithic listing. It will be made up of small segments called procedures and
you will work on one procedure at a time. This is called modularized approach of programming.

It permeates the Visual Basic language even the longest applications are written by breaking them into small,
well defined tasks. Each task is performed by a separate procedure that is written and tested separately from
the others. Procedures are useful for implementing repeated tasks.
The two types of procedures are subroutines and functions—the building blocks of your application.
Subroutines : A subroutine is a block of statements that carries out a well-defined task. The subroutine
begins with Sub and name of subroutine and its execution stops when EndSub statement is reached, and
control returns to the calling program. It is possible to exit a Subroutine prematurely with the Exit statement.

Functions : A function is similar to a subroutine, but a function returns a result. Subroutines perform a task
and don’t report anything to the calling program; functions commonly carry out calculations and report the
result. The statements that make up a function are placed in a pair of Function/End Function statements.
Because the function must report the result to the calling program, it must have a return type.

Subroutines
The idea of breaking a large application into smaller, more manageable sections is not new to
computing. Few tasks, programming or otherwise, can be managed as a whole. The event handlers
are just one example of breaking a large application into smaller tasks.

For example, when you write code for a control’s Click event, you concentrate on the event at hand
— namely, how the program should react to the Click event. What happens when the control is
double-clicked or when another control is clicked is something you will worry about later — in another
control’s event handler. This divide-and-conquer approach isn’t unique to programming events. It
permeates the Visual Basic language, and even the longest applications are written by breaking them
into small, well-defined, easily managed tasks. Each task is performed by a separate procedure that
is written and tested separately from the others. As mentioned earlier, the two types of procedures
supported by Visual Basic are subroutines and functions.

Subroutines usually perform actions and they don’t return any result. Functions, on the other hand,
perform some calculations and return a value. This is the only difference between subroutines and
functions. Both subroutines and functions can accept arguments, which are values you pass to the
procedure when you call it. Usually, the arguments are the values on which the procedure’s code
acts. Arguments and the related keywords are discussed in detail in the “VB.NET Arguments” section
later in this chapter.

A subroutine is a block of statements that carries out a well-defined task. The block of statements is
placed within a set of Sub. . .End Sub statements and can be invoked by name.

The following subroutine displays the current date in a message box and can be called by its name,
ShowDate():

Sub ShowDate()
MsgBox(Now().ToShortDateString)
End SubCode language: VB.NET (vbnet)
Normally, the task performed by a subroutine is more complicated than this; but even this simple
subroutine is a block of code isolated from the rest of the application. The statements in a subroutine
are executed, and when the End Sub statement is reached, control returns to the calling program. It’s
possible to exit a subroutine prematurely by using the Exit Sub statement.

All variables declared within a subroutine are local to that subroutine. When the subroutine exits, all
variables declared in it cease to exist.

Most procedures also accept and act upon arguments. The ShowDate() subroutine displays the
current date in a message box. If you want to display any other date, you have to implement it
differently and add an argument to the subroutine:

Sub ShowDate(ByVal birthDate As Date)


MsgBox(birthDate.ToShortDateString)
End SubCode language: VB.NET (vbnet)
birthDate is a variable that holds the date to be displayed; its type is Date. The ByVal keyword means
that the subroutine sees a copy of the variable, not the variable itself. What this means practically is
that the subroutine can’t change the value of the variable passed by the calling application. To display
the current date in a message box, you must call the ShowDate() subroutine as follows from within
your program:

ShowDate()Code language: VB.NET (vbnet)


To display any other date with the second implementation of the subroutine, use a statement like the
following:

Dim myBirthDate = #2/9/1960#


ShowDate(myBirthDate)Code language: VB.NET (vbnet)
Or, you can pass the value to be displayed directly without the use of an intermediate variable:

ShowDate(#2/9/1960#)Code language: VB.NET (vbnet)


If you later decide to change the format of the date, there’s only one place in your code you must edit:
the statement that displays the date from within the ShowDate() subroutine.
Sub Procedure Vs Function in VB.NET
.NET is a software framework that is designed and developed by Microsoft. The first version of the
.Net framework was 1.0 which came in the year 2002. In other words, it is a virtual machine for
compiling and executing programs written in different languages like C#, VB.Net, etc.

Sub Procedures:

A subprocedure is a group of VB.NET statements. It begins with a Sub keyword and ends with End
Sub keywords. A subprocedure is also called a subroutine. It is used to execute a certain block of
statements consists the body of the procedure. It is called explicitly by its name whenever it is
required to perform a certain task. It can be called any number of times. The subprocedure returns
control to the calling code after performing a task.
Structure of Subprocedure:
Sub <subname> [(parameter list)]
Vb statements
End Sub
Example:
Module module1
Sub SubDivide(ByVal num1 As Integer,
ByVal num2 As Integer)

Dim res As Integer

If (num2 <> 0) Then


res = num1/num2
Console.WriteLine("Divide by Zero is possible")
Else
Console.WriteLine("Divide by Zero is undefined")
End If
End Sub
Sub Main()
Dim a As Integer
Dim b As Integer
Dim res As Integer
Console.Write("Enter Number 1")
a = Console.ReadLine()
Console.Write("Enter Number 2")
b = Console.ReadLine()
SubDivide(a, b)
Console.WriteLine(res)

End Sub
End Module

Output:

Function Procedures:
A function procedure is a group of VB.NET statements. It begins with a Function keyword and
ends with an End Function keyword. It is generally used to perform a task and return a value back
to the calling code. It may have multiple return points to the calling code. A part from return
stamens, End Function, or Exit function also returns control to the calling procedure.
Structure of Function Procedure:
Function <Functionname> [(parameter list)] As return type
Vb statements
End Function
Example:
Module module1
Function FunctionDivide(ByVal num1 As Integer,
ByVal num2 As Integer) As Integer

Dim res As Integer

If (num2 <> 0) Then


res = num1/num2
return res
Else
Console.WriteLine("Divide by Zero is undefined")
End If
End Function
Sub Main()
Dim a As Integer
Dim b As Integer
Dim res As Integer
Console.Write("Enter Number 1")
a = Console.ReadLine()
Console.Write("Enter Number 2")
b = Console.ReadLine()
res = FunctionDivide(a, b)

Console.WriteLine(res)

End Sub
End Module

Comparison between SubProcedure and Function:

Parameters Sub Procedures Functions

A function is also not associated with


A subprocedure is not associated with an event.
1 an event.

A subprocedure is called, whenever it is


A function is called, whenever a value
required to perform certain tasks. It returns
is required to be returned to the calling
control to the calling code after performing a
code after performing a task.
2 task.

A subprocedure does not return a value to the Functions return a value to the calling
3 calling code. code.

A sub procedure cannot be used with an


Functions are used in an expression.
4 expression.

Subprocedure helps to make the code readable, In functions, it is not easy to modify
5 and easy to modify and debug. and debug the code.

A function is a specific type of


Sub procedure is a generalized type of function.
6 procedure
Parameters Sub Procedures Functions

A subprocedure is declared with the keyword A function is declared with the


7. Sub. keyword Function.
Argument-Passing Mechanisms
One of the most important topics in implementing your own procedures is the mechanism used to
pass arguments. The examples so far have used the default mechanism: passing arguments by
value. The other mechanism is passing them by reference. Although most programmers use the
default mechanism, it’s important to know the difference between the two mechanisms and when to
use each.

By Value versus by Reference


When you pass an argument by value, the procedure sees only a copy of the argument. Even if the
procedure changes it, the changes aren’t permanent; in other words, the value of the original variable
passed to the procedure isn’t affected. The benefit of passing arguments by value is that the
argument values are isolated from the procedure, and only the code segment in which they are
declared can change their values. This is the default argument-passing mechanism in Visual Basic
2008.

In VB 6, the default argument-passing mechanism was by reference, and this is something you
should be aware of, especially if you’re migrating VB 6 code to VB 2008.

To specify the arguments that will be passed by value, use the ByVal keyword in front of the
argument’s name. If you omit the ByVal keyword, the editor will insert it automatically because it’s the
default option. To declare that the Degrees() function’s argument is passed by value, use the ByVal
keyword in the argument’s declaration as follows:

Function Degrees(ByVal Celsius as Single) As Single


Return((9 / 5) * Celsius + 32)
End FunctionCode language: VB.NET (vbnet)
To see what the ByVal keyword does, add a line that changes the value of the argument in the
function:

Function Degrees(ByVal Celsius as Single) As Single


Return((9 / 5) * Celsius + 32)
Celsius = 0
End FunctionCode language: VB.NET (vbnet)
Now call the function as follows:

CTemp = InputBox("Enter temperature in degrees Celsius")


MsgBox(CTemp.ToString & " degrees Celsius are " & _
Degrees((CTemp)) & " degrees Fahrenheit")Code language: VB.NET (vbnet)
If you enter the value 32, the following message is displayed:

32 degrees Celsius are 89.6 degrees FahrenheitCode language: VB.NET (vbnet)


Replace the ByVal keyword with the ByRef keyword in the function’s definition and call the function as
follows:

Celsius = 32.0
FTemp = Degrees(Celsius)
MsgBox(Celsius.ToString & " degrees Celsius are " & FTemp & _
" degrees Fahrenheit")Code language: VB.NET (vbnet)
This time the program displays the following message:

0 degrees Celsius are 89.6 degrees FahrenheitCode language: VB.NET (vbnet)


When the Celsius argument was passed to the Degrees() function, its value was 32. But the function
changed its value, and upon return it was 0. Because the argument was passed by reference, any
changes made by the procedure affected the variable permanently. As a result, when the calling
program attempted to use it, the variable had a different value than expected.

Returning Multiple Values


If you want to write a function that returns more than a single result, you will most likely pass
additional arguments by reference and set their values from within the function’s code. The
CalculateStatistics() function, shown a little later in this section, calculates the basic statistics of a
data set. The values of the data set are stored in an array, which is passed to the function by
reference. The CalculateStatistics() function must return two values: the average and standard
deviation of the data set. Here’s the declaration of the CalculateStatistics() function:

Function CalculateStatistics(ByRef Data() As Double, _


ByRef Avg As Double, ByRef StDev As Double) As Integer

The function returns an integer, which is the number of values in the data set. The two important
values calculated by the function are returned in the Avg and StDev arguments:

Function CalculateStatistics(ByRef Data() As Double, _


ByRef Avg As Double, ByRef StDev As Double) As Integer
Dim i As Integer, sum As Double, sumSqr As Double, points As Integer
points = Data.Length
For i = 0 To points - 1
sum = sum + Data(i)
sumSqr = sumSqr + Data(i) ˆ 2
Next
Avg = sum / points
StDev = System.Math.Sqrt(sumSqr / points - Avg ˆ 2)
Return(points)
End Function
To call the CalculateStatistics() function from within your code, set up an array of Doubles and
declare two variables that will hold the average and standard deviation of the data set:

Dim Values(99) As Double


‘ Statements to populate the data set
Dim average, deviation As Double
Dim points As Integer
points = Stats(Values, average, deviation)
Debug.WriteLine points & ” values processed.”
Debug.WriteLine ”The average is ” & average & ” and”
Debug.WriteLine ”the standard deviation is ” & deviation
Using ByRef arguments is the simplest method for a function to return multiple values.
However, the definition of your functions might become cluttered, especially if you want to
return more than a few values. Another problem with this technique is that it’s not clear
whether an argument must be set before calling the function. As you will see shortly, it is
possible for a function to return an array or a custom structure with fields for any number of
values.

Passing Objects as Arguments


When you pass objects as arguments, they’re passed by reference, even if you have specified the
ByVal keyword. The procedure can access and modify the members of the object passed as an
argument, and the new value will be visible in the procedure that made the call.

The following code segment demonstrates this. The object is an ArrayList, which is an enhanced form
of an array. The ArrayList is discussed in detail later in the tutorial, but to follow this example all you
need to know is that the Add method adds new items to the ArrayList, and you can access individual
items with an index value, similar to an array’s elements. In the Click event handler of a Button
control, create a new instance of the ArrayList object and call the PopulateList() subroutine to
populate the list. Even if the ArrayList object is passed to the subroutine by value, the subroutine has
access to its items:

Private Sub Button1 Click(ByVal sender As System.Object, _


ByVal e As System.EventArgs) Handles Button1.Click
Dim aList As New ArrayList()
PopulateList(aList)
Debug.WriteLine(aList(0).ToString)
Debug.WriteLine(aList(1).ToString)
Debug.WriteLine(aList(2).ToString)
End Sub

Sub PopulateList(ByVal list As ArrayList)


list.Add("1")
list.Add("2")
list.Add("3")
End SubCode language: VB.NET (vbnet)
The same is true for arrays and all other collections. Even if you specify the ByVal keyword, they’re
passed by reference. A more elegant method of modifying the members of a structure from within a
procedure is to implement the procedure as a function returning a structure, as explained in the
section “Functions Returning Structures,” later in this chapter.
Introduction to Arguments

So far, to use a value in a procedure, we had to declare it. In some cases, a procedure may need an external
value in order to carry its assignment. A value that is supplied to a procedure is called an argument.

When creating a procedure that will use an external value, declare the argument that represents that value
between the parentheses of the procedure. For a sub procedure, the syntax you use would be:
Sub ProcedureName(Argument)

End Sub

If you are creating a function, the syntax would be:


Function ProcedureName(Argument) As DataType

Function Sub

The argument must be declared as a normal variable, omitting the Dim keyword. Here is an example that
creates a function that takes a string as argument:
Function CalculatePayroll(strName As String) As Double

Function Sub

A certain procedure can take more than one argument. In this case, in the parentheses of the procedure,
separate the arguments with a comma. Here is an example of a sub procedure that takes two arguments:
Sub EvaluateInvoice(EmplName As String, HourlySalary As Currency)

End Sub

In the body of a procedure that takes one or more arguments, use the argument(s) as you see fit as if they
were locally declared variables. For example, you can involve them with values inside of the procedure.
You can also exclusively use the values of the arguments to perform the assignment.

Calling a Procedure With Argument

To call a procedure that takes an argument, type its name and a space, followed by a value for each
argument between parentheses. The value provided for an argument is also called a parameter. If there is
more than one argument, separate them with a comma. Here is an example:
Module Exercise

Private Function GetFullName$(strFirst As String, _


strLast As String)
Dim FName As String

FName = strFirst & " " & strLast


GetFullName = FName
End Function

Public Function Main() As Integer


Dim FirstName, LastName As String
Dim FullName As String
Dim ComputerLanguage As String = "Visual Basic"

FirstName = inputbox("Enter First Name: ")


LastName = inputbox("Enter Last Name: ")

FullName = GetFullName(FirstName, LastName)

msgbox("Hello, " & FullName)


Welcome(ComputerLanguage)
Return 0
End Function

Sub Welcome(ByVal strLanguage As String)


msgbox("Welcome to the wonderful world of " & strLanguage)
End Sub

End Module

As mentioned previously, you can also use the Call keyword to call a procedure.

When you call a procedure that takes more than one argument, you must provide the values of the
arguments in the exact order they are listed inside of the parentheses of the function. Fortunately, you do
not have to. If you know the names of the arguments, you can type them in any order and provide a value
for each. To do that, on the right side of each argument, type the := operator followed by the desired value
for the argument. Here is an example:
Public Module Exercise

Private Function GetFullName$(MI As String, _


LastName As String, _
FirstName As String)
GetFullName = FirstName & " " & MI & " " & LastName
End Function

Public Function Main() As Integer


Dim FullName As String
Dim ComputerLanguage As String = "VBasic"

FullName = GetFullName(LastName:="Roberts", FirstName:="Alan", MI:="R.")

MsgBox("Hello " & FullName)


Call Welcome(ComputerLanguage)
Return 0
End Function

Private Sub Welcome(ByVal strLanguage As String)


MsgBox("Welcome to the wonderful world of " & strLanguage)
End Sub

End Module
Practical Learning: Passing Arguments to a Procedure

1. To pass arguments to a function, change the file as follows (when you type the argument, Microsoft
Visual Studio, actually the Visual Basic language parser, will add the ByVal keywords; in the next
sections, we will learn what that keyword means; for now, keep but ignore it):

Public Module Rectangle

Private Function GetValue(TypeOfValue As String) As Double


Dim Value As Double

Value = InputBox("Enter the " & TypeOfValue & ":")


Return Value
End Function
Private Function CalculatePerimeter(Length As Double, _
Width As Double) As Double
CalculatePerimeter = (Length + Width) * 2
End Function

Public Function Main() As Integer


Dim L As Double, W As Double
Dim Perimeter As Double

L = GetValue("Length")
W = GetValue("Width")
Perimeter = CalculatePerimeter(L, W)

MsgBox("=-= Square Characteristics=-=" & vbCrLf & _


"Length: " & L & vbCrLf & _
"Width: " & W & vbCrLf & _
"Perimeter: " & Perimeter)
Return 0
End Function

End Module

2. Execute the application


3. Enter the length as 44.14 and the with as 30.76
4. Close the message box and the DOS window

Techniques of Passing Arguments


5.
Passing Arguments (By Value)

6. When calling a procedure that takes an argument, we were supplying a value for that argument.
When this is done, the procedure that is called makes a copy of the value of the argument and makes
that copy available to the calling procedure. That way, the argument itself is not accessed. This is
referred to as passing an argument by value. This can be reinforced by typing the ByVal keyword on
the left side of the argument. Here is an example:
7. Private Sub Welcome(ByVal strLanguage As String)
8. MsgBox("Welcome to the wonderful world of " & strLanguage)
9. End Sub
10. If you create a procedure that takes an argument by value and you have used the ByVal keyword on
the argument, when calling the procedure, you do not need to use the ByVal keyword; just the name
of the argument is enough, as done in the examples on arguments so far. Here is an example:
11. Public Module Exercise
12.
13. Public Function Main() As Integer
14. Dim ComputerLanguage As String = "Visual Basic"
15.
16. Welcome(ComputerLanguage)
17. Return 0
18. End Function
19.
20. Private Sub Welcome(ByVal strLanguage As String)
21. MsgBox("Welcome to the wonderful world of " & strLanguage)
22. End Sub
23.
24. End Module
25. This would produce:
Passing Arguments By Reference

An alternative to passing arguments as done so far is to pass the address of the argument to the called
procedure. When this is done, the called procedure does not receive a simple copy of the value of the
argument: the argument is accessed by its address. That is, at its memory address. With this technique, any
action carried on the argument will be kept. If the value of the argument is modified, the argument would
now have the new value, dismissing or losing the original value it had. This technique is referred to as
passing an argument by reference. Consider the following program:
Public Module Exercise

Private Function Addition#(ByVal Value1 As Double, ByVal Value2 As Double)


Value1 = InputBox("Enter First Number: ")
Value2 = InputBox("Enter Second Number: ")

Addition = Value1 + Value2


End Function

Public Function Main() As Integer


Dim Result As String
Dim Number1, Number2 As Double

Result = Addition(Number1, Number2)


MsgBox(Number1 & " + " & Number2 & " = " & Result)
Return 0
End Function

End Module

Here is an example of running the program:


Notice that, although the values of the arguments were changed in the Addition() procedure, at the end of
the procedure, they lose the value they got in the function. If you want a procedure to change the value of
an argument, you can pass the argument by reference.

To pass an argument by reference, on its left, type the ByRef keyword. This is done only when creating the
procedure. When the called procedure finishes with the argument, the argument would keep
whatever modification was made on its value. Now consider the same program as above but with arguments
passed by reference:
Public Module Exercise

Private Function Addition#(ByRef Value1 As Double, ByRef Value2 As Double)


Value1 = InputBox("Enter First Number: ")
Value2 = InputBox("Enter Second Number: ")

Addition = Value1 + Value2


End Function

Public Function Main() As Integer


Dim Result As String
Dim Number1, Number2 As Double

Result = Addition(Number1, Number2)


MsgBox(Number1 & " + " & Number2 & " = " & Result)
Return 0
End Function

End Module

Here is an example of running the program:

Using this technique, you can pass as many arguments by reference and as many arguments by value as you
want. As you may guess already, this technique is also used to make a sub procedure return a value, which a
regular sub routine cannot do. Furthermore, passing arguments by reference allows a procedure to return as
many values as possible while a regular function can return only one value.

Practical Learning: Passing Arguments by Reference

1. To pass an argument by reference, change the file as follows:

Public Module Rectangle

Private Sub GetValues(ByRef Length As Double, ByRef Width As


Double)
Length = InputBox("Enter the length:")
Width = InputBox("Enter the width:")
End Sub

Private Function CalculatePerimeter(ByVal Length As Double, _


ByVal Width As Double) As
Double
CalculatePerimeter = (Length + Width) * 2
End Function

Private Function CalculateArea(ByVal Length As Double, _


ByVal Width As Double) As
Double
CalculateArea = Length * Width
End Function

Private Sub ShowCharacteristics(ByVal Length As Double, _


ByVal Width As Double)
Dim Result As String

Result = "=-= Rectangle Characteristics =-=" & vbCrLf & _


"Length: " & vbTab & vbTab & CStr(Length) &
vbCrLf & _
"Width: " & vbTab & vbTab & CStr(Width) &
vbCrLf & _
"Perimeter: " & vbTab & _
CalculatePerimeter(Length, Width) & vbCrLf & _
"Area: " & vbTab & vbTab & _
CalculateArea(Length, Width)
MsgBox(Result)
End Sub

Public Function Main() As Integer


Dim L As Double, W As Double

GetValues(L, W)
ShowCharacteristics(L, W)
Return 0
End Function

End Module

2. Execute the application


3. Enter the length as 24.55 and the width as 22.85
4. Close the message box and the DOS window
Visual Basic Optional Parameters
In visual basic, the optional parameters have been introduced to specify the parameters as optional while defining
the methods, indexers, constructors, and delegates.

Generally, while calling the method we need to pass all the method parameters. In case, if we specify a few of method
parameters as an optional, then we can omit those parameters while calling the method because the optional
parameters are not mandatory.

If we want to make the parameter as an optional, we need to define a parameter with Optional keyword and assign the
default value to that parameter as part of its definition in methods, indexers, constructors, and delegates.

While calling the method, if no argument is sent for an optional parameter, then the default value will be used otherwise
it will use the value which is sent for that parameter.

Following is the example of defining the optional parameters in a method.

Public Sub GetDetails(ByVal id As Integer, ByVal name As String, Optional ByVal location
As String = "Hyderabad")
' your code
End Sub

If you observe the above method, we made the location parameter as optional by assigning the default value
(Hyderabad). So, while accessing GetDetails() method, if no argument sent for location parameter, then by default it
will consider “Hyderabad” value otherwise it will use the value which is sent for that parameter.

The defined GetDetails() method can be accessed as shown below.

GetDetails(1,"Suresh");
GetDetails(1,"Suresh", "Chennai");

While defining the optional parameters, we need to make sure that the optional parameters are defined at the end of
the parameter list, after any required parameters like as we defined in the above method otherwise we will get the
compile-time error like “optional parameters must appear after all required parameters”.

Following is the invalid way of defining the optional parameters in a method.

Public Sub GetDetails(ByVal id As Integer, ByVal Optional location As String = "Hyderaba


d", ByVal name As String)
' your code
End Sub
The above method will throw the compile-time error because we defined a required parameter (name) after the optional
parameter (location). As per rules, the optional parameters must be defined at the end of the parameter list.

Visual Basic Multiple Optional Parameters


In case, if you want to define multiple optional parameters, then the method declaration must be like as shown below.

Public Sub GetDetails(ByVal id As Integer, Optional ByVal name As String = "Suresh", Opt
ional ByVal location As String = "Hyderabad")
' your code
End Sub
The defined GetDetails() method can be accessed like as shown below.

GetDetails(1);
GetDetails(1, "Rohini");
GetDetails(1, "Trishi", "Guntur");
While calling the method, if we provide an argument for any of succession optional parameters, then we must need to
provide an argument for all the preceding optional parameters and the comma-separated gaps in the argument list are
not supported.

Following is the invalid way of defining the optional parameters in a method.

GetDetails(1, , "Guntur");
The above caller method will throw a compile-time error like “Argument missing” because we provided an argument
for the third parameter but not for a second.

However, if you know the name of the third parameter, then you can use a named argument to send a value like as
shown below.

GetDetails(1, location:="Guntur");
This is how we can skip preceding optional parameters by using named arguments in caller methods.

Visual Basic Optional Parameters Example


Following is the example of defining the optional parameters during the method declaration in visual basic.

Module Module1
Sub Main(ByVal args As String())
GetDetails(1)
GetDetails(1, "Rohini")
GetDetails(1, "Trishi", "Guntur")
GetDetails(1, location:="Guntur")
Console.ReadLine()
End Sub
Public Sub GetDetails(ByVal id As Integer, Optional ByVal name As String = "Suresh",
Optional ByVal location As String = "Hyderabad")
Console.WriteLine("Id:{0}", id)
Console.WriteLine("Name:{0}", name)
Console.WriteLine("Location:{0}", location)
End Sub
End Module

If you observe the above example, the GetDetails() method has one required parameter (id) and two optional
parameters (name, location).

When we execute the above program, we will get the result like as shown below.
****Only Required Parameter****
Id:1
Name:Suresh
Location:Hyderabad

****Required Parameter & One Optional Parameter****


Id:1
Name:Rohini
Location:Hyderabad

****Both Required & Optional Parameters****


Id:1
Name:Trishi
Location:Guntur

****Required & Second Optional Parameter****


Id:1
Name:Suresh
Location:Guntur

This is how we can define the optional parameters in methods, indexers, constructors, and delegates based on our
requirements.

In visual basic, we can also achieve the optional parameters by using method overloading functionality. Generally,
the method overloading functionality will allow us to create multiple methods with the same name but with different
parameters.

To know more about overloading functionality in visual basic, check method overloading.

Visual Basic Optional Parameters Overview


Following are the important points which we need to remember about optional parameters in visual basic.

 The optional parameters have been introduced to specify the parameters as optional while defining
the methods, indexers, constructors, and delegates.
 To make the parameter as optional, we need to assign the default value to that parameter as part of its definition
in methods, indexers, constructors, and delegates.
 While calling the method, if no argument is sent for an optional parameter, then the default value will be used.
 While defining the optional parameters, we need to make sure that the optional parameters are defined at the
end of the parameter list, after any required parameters.
Visual Basic Named Parameters
In visual basic, the named parameters have been introduced to pass the method arguments with parameter name rather than
with the method parameter’s position in the parameter list.

Generally, while calling the method we need to pass all the method arguments in the same sequence of parameters in the
method definition. If we use named parameters, we don’t need to worry about the order or sequence of parameters while
calling the method.

In named parameters, the parameter values will be mapped to the right parameter based on the parameter name. So, while
calling the methods we can send the parameters in any sequence or order if we specify the parameter name.

For example, we have a GetDetails() method with three parameters (id, name, location) like as shown below.

Public Sub GetDetails(ByVal id As Integer, ByVal name As String, ByVal location As String)
' your code
End Sub
In the standard way, we will call the above method by sending the arguments in the same order or position however we
defined the parameters in the method definition like as shown below.

GetDetails(1, "Trishi", "Guntur");


In case, if we forgot and send the parameters in different order like as shown following we will get the compile-time error like
“The best overloaded method for 'GetDetails(int, string, string)' has some invalid arguments”.

GetDetails("Trishi", 1, "Guntur");
By using named parameters, we call the above method by sending the parameters in any sequence or order like as shown
below.

GetDetails(id: 1, name: "Trishi", location: "Guntur");


GetDetails(name: "Trishi", id: 1, location: "Guntur");
GetDetails(location: "Guntur", name: "Trishi", id: 1);
We can also use the named arguments with positional arguments as long as they are not followed by any positional
arguments like as shown below.
GetDetails(1, "Trishi", location: "Guntur");
Following is the invalid way of using named and positional arguments while calling the method.

GetDetails(name: "Trishi", 1, location: "Guntur");


The above method call will throw the compile-time exception like “Named argument 'name' is used out-of-position but is
followed by an unnamed argument” because we defined the positional argument followed by named argument (name).

Visual Basic Named Parameters Example


Following is the example of calling the method by sending the parameters in different sequences using named parameters in
visual basic.

Module Module1
Sub Main(ByVal args As String())
GetDetails(1, "Suresh", "Hyderabad")
GetDetails(name:="Rohini", id:=2, location:="Guntur")
GetDetails(3, "Trishi", location:="Guntur")
Console.ReadLine()
End Sub
Public Sub GetDetails(ByVal id As Integer, ByVal name As String, ByVal location As Strin
g)
Console.WriteLine("Id:{0}", id)
Console.WriteLine("Name:{0}", name)
Console.WriteLine("Location:{0}", location)
End Sub
End Module
If you observe the above example, we are calling the GetDetails() method by sending the parameters in different positions
with named parameters.

When we execute the above visual basic program, we will get the result like as shown below.

****Calling Method Normally****


Id:1
Name:Suresh
Location:Hyderabad

****Calling Method with Named Arguments****


Id:2
Name:Rohini
Location:Guntur

****Calling Method with Named & Positional Arguments****


Id:3
Name:Trishi
Location:Guntur
This is how we can use the named parameters in visual basic to pass the method arguments with parameter name rather than
with the method parameter’s position.

Visual Basic Named Parameters Overview


Following are the important points which we need to remember about named parameters in visual basic.

 The named parameters have been introduced in visual basic to pass the method arguments with parameter name
rather than with the method parameter’s position in the parameter list.
 In named parameters, the parameter values will be mapped to the right parameter based on the parameter name.
 We can send the parameters in any sequence or order if we specify the parameters name while calling the methods.
 While calling the method, we can use the named arguments with positional arguments as long as they are not
followed by any positional arguments.
Named Arguments
You learned how to write procedures with optional arguments and how to pass a variable number of
arguments to the procedure. The main limitation of the argument-passing mechanism, though, is the
order of the arguments. By default, Visual Basic matches the values passed to a procedure to the
declared arguments by their order (which is why the arguments you’ve seen so far are called
positional arguments).

This limitation is lifted by Visual Basic’s capability to specify named arguments. With named
arguments, you can supply arguments in any order because they are recognized by name and not by
their order in the list of the procedure’s arguments. Suppose you’ve written a function that expects
three arguments: a name, an address, and an email address

Function Contact(Name As String, Address As String, EMail As String)Code language: VB.NET


(vbnet)
When calling this function, you must supply three strings that correspond to the arguments Name,
Address, and EMail, in that order. However, there’s a safer way to call this function: Supply the
arguments in any order by their names. Instead of calling the Contact() function as follows:

Contact("Peter Evans", "2020 Palm Ave., Santa Barbara, CA 90000", _


"[email protected]")Code language: VB.NET (vbnet)
you can call it this way:

Contact(Address:="2020 Palm Ave., Santa Barbara, CA 90000", _


EMail:="[email protected]", Name:="Peter Evans")Code language: VB.NET (vbnet)
The := operator assigns values to the named arguments. Because the arguments are passed by
name, you can supply them in any order.

To test this technique, enter the following function declaration in a form’s code:

Function Contact(ByVal Name As String, ByVal Address As String, _


ByVal EMail As String) As String

Debug.WriteLine(Name)
Debug.WriteLine(Address)
Debug.WriteLine(EMail)
Return ("OK")

End FunctionCode language: VB.NET (vbnet)


Then call the Contact() function from within a button’s Click event with the following statement:

Debug.WriteLine( _
Contact(Address:="2020 Palm Ave., Santa Barbara, CA 90000", _
Name:="Peter Evans", EMail:="[email protected]"))Code language: VB.NET (vbnet)
You’ll see the following in the Immediate window:

Peter Evans
2020 Palm Ave., Santa Barbara, CA 90000
[email protected]
OK
The function knows which value corresponds to which argument and can process them the same way
that it processes positional arguments. Notice that the function’s definition is the same, whether you
call it with positional or named arguments. The difference is in how you call the function and not how
you declare it.

Named arguments make code safer and easier to read, but because they require a lot of typing, most
programmers don’t use them. Besides, when IntelliSense is on, you can see the definition of the
function as you enter the arguments, and this minimizes the chances of swapping two values by
mistake.

You might also like