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

Visual Basic NXT

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Visual Basic NXT

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

[Year]

[Type the company


name]

user

[TYPE THE DOCUMENT TITLE]


[Type the abstract of the document here. The abstract is typically a short summary of the contents of
the document. Type the abstract of the document here. The abstract is typically a short summary of the
contents of the document.]
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm

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

 Common Language Runtime (CLR)


 CTS is a specification created by Microsoft.The .NET Framework provides a run-time environment
called the common language runtime, which runs the code and provides services that make the
development process easier.
 Code that you develop with a language compiler that targets the runtime is called managed code
 CTS is designed as a singly rooted object hierarchy with System.Object as the base type from
which all other types are derived.
 The .Net Framework Class Library
.NET implementations include classes, interfaces, delegates, and value types that expedite and optimize the
development process and provide access to system functionality.

 Common Language Specification


A Common Language Specification (CLS) is a document that says how computer programs can be
turned into Common Intermediate Language (CIL) code.
Microsoft has defined CLS which are nothing but guidelines for languages to follow so that it can
communicate with other . NET languages in a seamless manner.

 Common Type System


The Common Type System (CTS) is a standard for defining and using data types in the .NETframework.
CTS defines a collection of data types, which are used and managed by the run time to facilitate cross-
language integration.

 Metadata and Assemblies


 Windows Forms.
 ASP.Net and ASP.Net AJAX(Asynchronous JavaScript And
XML)
 ADO.Net(Active X Data Objevt
 Windows Workflow Foundation (WF)
 Windows Presentation Foundation
 Windows Communication Foundation (WCF)
 LINQ
For the jobs each of these components perform, please see ASP.Net - Introduction, and for details of each
component, please consult Microsoft's documentation.

Integrated Development Environment (IDE) For VB.Net


Microsoft provides the following development tools for VB.Net programming −

 Visual Studio 2010 (VS)

 Visual Basic 2010 Express (VBE)

 Visual Web Developer these two are free


Using these tools, you can write all kinds of VB.Net programs from simple command-line applications to more
complex applications. Visual Basic Express and Visual Web Developer Express edition are trimmed down versions
of Visual Studio and has the same look and feel. They retain most features of Visual Studio. In this tutorial, we have
used Visual Basic 2010 Express and Visual Web Developer (for the web programming chapter).
You can download it from here. It gets automatically installed in your machine. Please note that you need an active
internet connection for installing the express edition.

Writing VB.Net Programs on Linux or Mac OS


Although the.NET Framework runs on the Windows operating system, there are some alternative versions that work
on other operating systems.
Mono is an open-source version of the .NET Framework which includes a Visual Basic compiler and runs
on several operating systems, including various flavors of Linux and Mac OS.

Version number .NET Framework CLR version Release date


1.0 1.0 2002-02-13
1.1 1.1 2003-04-24
2.0 2.0 2005-11-07
3.0 2.0 2006-11-06
3.5 2.0 2007-11-19
4.0 4 2010-04-12
4.5 4 2012-08-15
4.5.1 4 2013-10-17
4.5.2 4 2014-05-05
4.6 4 2015-07-20
4.6.1 4 2015-11-17
4.6.2 4 2016-08-02
4.7 4 2017-04-05
4.7.1 4 2017-10-17

Evolution of Visual Studio:


The first version of VS(Visual Studio) was released in 1997, named as Visual Studio 97 having version number 5.0.
The latest version of Visual Studio is 15.0 which was released on March 7, 2017. It is also termed as Visual Studio
2017. The supported .Net Framework Versions in latest Visual Studio is 3.5 to 4.7. Java was supported in old
versions of Visual Studio but in the latest version doesn’t provide any support for Java language.
Visual Studio .NET Framework
VS 6.0 Last one before .NET
VS .NET 2002 (7.0) 1.0
VS .NET 2003 (7.1) 1.1
VS 2005 (8.0) 2.0
VS 2008 (9.0) 3.5
VS 2010 (10.0) 4.0
VS 2012 (11.0) 4.5
VS 2013 (12.0) 4.5.1
VS 2015 (14.0) 4.6
VS 2017 RTW (15.0) 4.6.1
VS 2017 version 15.3 4.6.1
VS 2017 version 15.5 4.6.1
VS 2017 version 15.6 4.6.1
VS 2017 version 15.7 4.7.1
VS 2017 version 15.8 4.7.1
VS 2017 version 15.9 4.7.1
Mono:
Mono Framework – a free, open-source, cross-platform implementation of the .NET Framework.It
enables to run Microsoft .NET applications cross-platform and also to bring better development tools to Linux
developers.
Mono can be run on many operating systems including
Android,

BSD,
Berkeley Software Distribution
The Berkeley Software Distribution (BSD) was an operating system based on Research Unix,Linux
It is older than Linux.
Apple's free Darwin operating system and commercial Mac OS X are also based on BSD

iOS

Linux

Windows

Solaris

UNIX.

Completed till here.Next on tenth/September.


VB.Net - Program Structure
VB.Net Hello Example
A VB.Net program basically consists of the following parts –

 Namespace declaration
o This article describe namespaces in VB.Net. Group of code having a specific name is
a Namespace. In a Namespace the groups of components are somehow related to each
other. Namespaces are similar in concept to a folder in a computer file system.
o Namespaces prevent ambiguity and simplify references when using large groups of objects such
as class libraries.
o Namespaces are used to organize code into logical groups and to prevent name collisions that can
occur especially when your code base includes multiple libraries.
o The namespaces cannot be created as objects
o For namespace we use ‘using’ declaration.

 A class or module
 One or more procedures
 Variables
 The Main procedure
 Statements & Expressions
 Comments
Example:
Console application.(Command line par jo run kare

Imports System --namespace

Module Abc

'This program will display Students BCA/IT Sem V!

Sub Main()

Console.WriteLine("Hello Students BCA/IT Sem V!")

Console.ReadKey()

End Sub

End Module

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

Hello Students BCA/IT Sem V!


Let us look various parts of the above program −

 The first line of the program Imports System is used to include the System namespace in the program.

 The next line has a Module declaration, the module Abc. VB.Net is completely object oriented, so every
program must contain a module of a class that contains the data and procedures that your program uses.
o Classes or Modules generally would contain more than one procedure.
o Procedures contain the executable code, or in other words, they define the behavior of the class.
o A procedure could be any of the following −

 Function  Set
 Sub  AddHandler
 Operator  RemoveHandler
 Get  RaiseEvent
 The next line('This program will display Hello, Students BCA/IT Sem V!) will be ignored by the compiler and it has
been put to add additional comments in the program.
 The next line defines the Main procedure, which is the entry point for all VB.Net programs. The Main
procedure states what the module or class will do when executed.

 The Main procedure specifies its behavior with the statement


Console.WriteLine("Hello World") WriteLine is a method of the Console class defined in
the System namespace. This statement causes the message " Hello, Students BCA/IT Sem V!" to be
displayed on the screen.

 The last line Console.ReadKey() is for the VS.NET Users. This will prevent the screen from running and
closing quickly when the program is launched from Visual Studio .NET.

 Studio .NET.

Compile & Execute VB.Net Program


If you are using Visual Studio.Net IDE, take the following steps −
 Start Visual Studio.
 On the menu bar, choose File → New → Project.
 Choose Console Application.
 Specify a name and location, and then choose the OK button.
 The new project appears in Solution Explorer.
 Write code in the Code Editor.
 Click the Run button or the F5 key to run the project. A Command Prompt window appears that contains
the line Hello, Students BCA/IT Sem V!.

You can compile a VB.Net program by using the command line instead of the Visual Studio IDE –

 Open a text editor and add the above mentioned code.


 Save the file as hello.vb
 Open the command prompt tool and go to the directory where you saved the file.

 Type vbc hello.vb and press enter to compile your code.


 If there are no errors in your code the command prompt will take you to the next line and would
generate hello.exe executable file.
 Next, type hello to execute your program.
 You will be able to see " Hello, Students BCA/IT Sem V!" printed on the screen.
VB.Net
Visual Basic .NET is an object-oriented computer programming language on the .NET
Framework.
 It is an evolution of classic Visual Basic language.
 But it is not backwards-compatible with VB6.
and any code written in the old versionfsgdgdghdhdhdshsh
does not compile under VB.NET.

 types (Short, Integer, Long, String, Boolean, etc.) and user-defined types, events, and even assemblies. All
objects inherits from the base class Object.

 VB.NET is implemented by Microsoft's .NET framework. Therefore, it has full access to all the libraries in
the .Net Framework. It's also possible to run VB.NET programs on Mono, the open-source alternative to
.NET, not only under Windows, but even Linux or Mac OSX.

 The following reasons make VB.Net a widely used professional language

Strong Programming Features VB.Net


VB.Net has numerous strong programming features that make it endearing to multitude of programmers worldwide.
Let us mention some of these features −

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

V
B.Net is an object-oriented programming language. In
Object-Oriented Programming methodology, a program
consists of various objects that interact with each other
by means of actions. The actions that an object may
take are called methods. Objects of the same kind are
said to have the same type or, more often, are said to
be in the same class.
When we consider a VB.Net program, it can be defined as a collection of objects that communicate via invoking
each other's methods. Let us now briefly look into what do class, object, methods and instance variables mean.
 Namespace-
o Namespace is logical division of class, structure and interface OR way to organize your Visual
Basic
o NET code is through the use of namespaces. Namespaces are a way of grouping type names
and reducing the chance of name collisions.
o A namespace simply provides a named group of classes, structures, enumerations, delegates,
interfaces and other namespaces.
o Namespace allows logical separation of objects improving the maintainability and usage.

 Module-
o A module is a logical collection of code within an Assembly.

o "A Module is a portable executable file, such as type.dll or application.exe, consisting of


one or more classes and interfaces."
o You can have multiple modules inside an Assembly, and each module can be written in different
. NET languages ().
o Assemblies contain modules. Modules contain classes.

 Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as
behaviors - wagging, barking, eating, etc. An object is an instance of a class.

 Class – A class can be defined as a template/blueprint that describes the behaviors/states that objects of
its type support.

o The terms class and object are sometimes used interchangeably.


o But in fact, classes describe the type of objects.
o While objects are usable instances of classes.

o instantiation.
So, the act of creating an object is called
o Using the blueprint analogy,
 a class is a blueprint,
 and an object is a building made from that blueprint.
o Methods − A method is basically a behavior. A class can contain many methods. It is in methods
where the logics are written, data is manipulated and all the actions are executed.
 Functions returning values after processing are called Functions.
 Functions returning no value are called Sub Procedures.
 The Sub procedure performs a task and then returns control to the calling code, but it
does not return a value to the calling code.
o Instance Variables − Each object has its unique set of instance variables. An object's state is
created by the values assigned to these instance variables.
 Interface-
o An interface is a specification for a set of class members, not an implementation. An Interface is
a reference type and it contains only abstract members such as Events, Methods, Properties etc.
o It contain only declaration for its members and implementation defined as separate entities from
classes.
o Any implementation of the abstract methods under these interfaces must be placed in class that
implements them.

o An interface is a completely " abstract class", which can only contain abstract
methods and properties (with empty bodies):
Namespace in code and description.
Examples:
Every program by default uses a Root namespace

Namespace Ritesh

First

second

End Namespace imports

 Import System Ritesh.First


 Import System.Collections
Imports System

Namespace Birds 'user defined namespace Bird

Class Parrot 'Parrot is a class in the namespace Birds

Public Shared Function fly() 'Fly is a function in this Class


Console.WriteLine("Parrot can fly")
End Function

Shared Function color() ' color is another function in parrot class


Console.WriteLine("normally Parrots are green")
End Function

Public Shared Function type()


Console.WriteLine("Different type of parrot are found around the world")
End Function

End Class
End Namespace
Module MCA
Public Function myfunction()
Dim P As Birds.Parrot
P = New Birds.Parrot()
P.type() 'accessing member of the namespace bird and the class parrot
End Function

Sub main()
Console.Clear()
Birds.Parrot.fly() 'accessing member of the namespace
Birds.Parrot.color() 'another way to access member of the namespace
myfunction()
End Sub
End Module

this is done on 28th/9


Examples:

Module in code:

Module BCAIT
Sub Main()

Module2.Increment()
Module2.Increment()
Module2.Increment()

End Sub
End Module

Module Module2
Dim _value As Integer
Sub Increment()
Console.WriteLine(_value)
_value += 1

End Sub
End Modulede
*This module has a field, _value, which is shared automatically (implicitly).
Class in code:

Class Example

Private evalue As Integer

Public Sub New() ‘constructor of the class in vb.net


evalue = 2
End Sub
Public Function Value() As Integer
Return evalue * 2
End Function
End Class

Module cait
Sub Main() ' Step 1: create a new instance of Example Class.
Dim x As Example = New Example()
Console.WriteLine(x.Value())
End Sub

End Module

Module mybox
Class Box
Public length As Double ' Length of a box
Public breadth As Double ' Breadth of a box
Public height As Double ' Height of a box
End Class
Sub Main()
Dim Box1 As Box = New Box() ' Declare Box1 of type Box
Dim Box2 As Box = New Box() ' Declare Box2 of type Box
Dim volume As Double = 0.0 ' Store the volume of a box here

' box 1 specification


Box1.height = 5.0
Box1.length = 6.0
Box1.breadth = 7.0

' box 2 specification


Box2.height = 10.0
Box2.length = 12.0
Box2.breadth = 13.0

'volume of box 1
volume = Box1.height * Box1.length * Box1.breadth

Console.WriteLine(" Volume of Box1 : {0}", volume)


'volume of box 2
volume = Box2.height * Box2.length * Box2.breadth
Console.WriteLine("Volume of Box2 : {0}", volume)
Console.ReadKey()
End Sub
End Module
Module functions

Public bla As Integer = 10


Public bla2 As Integer = 20

Public Function addnumbers(ByVal number1 As Integer, ByVal number2 As Integer)


Return number1 + number2
End Function

End Module

Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


Button1.Click
TextBox3.Text = addnumbers(bla, bla2)
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


Button2.Click
MessageBox.Show(addnumbers(TextBox1.Text, TextBox2.Text))
MessageBox.Show(functions.addnumbers(TextBox1.Text, TextBox2.Text))
End Sub

End Class

Interface-

Public Interface IBird


Sub voice()
Sub Breathe()

End Interface

Public Class Bird


Implements IBird
Public Sub voice Implements IBird.voice
Console.WriteLine("♫ ♫ ♫")
End Sub

Public Sub Breathe() Implements IBird.Breathe


Console.WriteLine("Breathing...")
End Sub

Public Sub Peck()


Console.WriteLine("Peck, peck!")
End Sub

End Class.
Module module1
Dim brd as bird
Sub main(
Brd=new bird
Brd.breate(
Brd.voice(
Brd.peck(
End sub
End module
Start next on 3o/9
Now as you have got some glipse of the code we write in .net.
Let know the language properly.

A. Identifiers
An identifier is a name used to identify a class, variable, function, or any other user-defined item.
B. Keywords
a) Reserve words
b) a word or concept of great significance.
c) a word which acts as the key to a cipher or code.
d) Keywords are ideas and topics that define what your content is about.
e) a word used to classify or organize digital content, or to facilitate an online search for information:

AddHandler AddressOf Alias And AndAlso As Boolean

ByRef Byte ByVal Call Case Catch CBool

CByte CChar CDate CDec CDbl Char CInt

Class CLng CObj Const Continue CSByte CShort

CSng CStr CType CUInt CULng CUShort Date

Decimal Declare Default Delegate Dim DirectCast Do

Double Each Else ElseIf End End If Enum

Erase Error Event Exit False Finally For

Friend Function Get GetType GetXML Global GoTo


Namespace
Handles If Implements Imports In Inherits Integer

Interface Is IsNot Let Lib Like Long

Loop Me Mod Module MustInherit MustOverride MyBase

MyClass Namespace Narrowing New Next Not Nothing

Not Not Object Of On Operator Option


Inheritable Overridable
Optional Or OrElse Overloads Overridable Overrides ParamArray

Partial Private Property Protected Public RaiseEvent ReadOnly

ReDim REM Remove Resume Return SByte Select


Handler
Set Shadows Shared Short Single Static Step

Stop String Structure Sub SyncLock Then Throw

To True Try TryCast TypeOf UInteger While

Widening With WithEvents WriteOnly Xor


C. Datatypes:
Data types determine the type of data that any variable can store.
 Boolean: the allocated storage depends on the platform of implementation. Its value
can be either True or False.

 Byte: allocated storage space of 1 byte. Values range from 0 to 255 (unsigned).

 Char: allocated a space of 2 bytes. Values range from 0 to 65535 (unsigned).

 Date: allocated storage space of 8 bytes. Values range from 0:00:00 (midnight)
January 1, 0001 to 11:59:59 PM of December 31, 9999.

 Integer: has a storage space of 4 bytes. Values range between -2,147,483,648 to


2,147,483,647 (signed).

 Long: has a storage space of 8 bytes. Numbers range from -


9,223,372,036,854,775,808 to 9,223,372,036,854,775,807(signed).

 String: The storage space allocated depends on the platform of implementation.


Values range from 0 to about 2 billion Unicode characters.

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

check = CBool(a = b)
2
CByte(expression)
Converts the expression to Byte data type.

3
CChar(expression)
Converts the expression to Char data type.
Dim aChar As Char
aString = " BCD"
' The following line of code sets aChar to "B".
aChar = CChar(aString)

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

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

6
CDec(expression)
Converts the expression to Decimal data type.
Dim aDouble As Double
Dim aDecimal As Decimal
aDouble = 10000000.0587
' The following line of code sets aDecimal to 10000000.0587.
aDecimal = CDec(aDouble)

7
CInt(expression)
Converts the expression to Integer data type.
Dim aDbl As Double
Dim anInt As Integer
aDbl = 2345.5678
' The following line of code sets anInt to 2346.

anInt = CInt(aDbl)
8
CLng(expression)
Converts the expression to Long data type.
Dim aDbl1, aDbl2 As Double
Dim aLng1, aLng2 As Long
aDbl1 = 25427.45
aDbl2 = 25427.55
' The following line of code sets aLng1 to 25427.
aLng1 = CLng(aDbl1)
' The following line of code sets aLng2 to 25428.
aLng2 = CLng(aDbl2)

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

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

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

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

13
CStr(expression)
Converts the expression to String data type.
Dim aDouble As Double
Dim aString As String
aDouble = 437.324
‘The following line of code sets aString to "437.324".
aString = CStr(aDouble)

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

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

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

 CBool (expression): converts the expression to a Boolean data type.


 CDate(expression): converts the expression to a Date data type.
 CDbl(expression): converts the expression to a Double data type.
 CByte (expression): converts the expression to a byte data type.
 CChar(expression): converts the expression to a Char data type.
 CLng(expression): converts the expression to a Long data type.
 CDec(expression): converts the expression to a Decimal data type.
 CInt(expression): converts the expression to an Integer data type.
 CObj(expression): converts the expression to an Object data type.
 CStr(expression): converts the expression to a String data type.
 CSByte(expression): converts the expression to a Byte data type.
 CShort(expression): converts the expression to a Short data type.mete variato theble
 CTYPE(expression:converts the first paratype mentioned as the second
parameter.A=ctype(b,String

D. Variables
 A variable is nothing but a name given to a storage area that our programs can manipulate.

 A variable is a simple name used to store the value of a specific data type in computer memory.

 Dim [Variable_Name] As [Defined Data Type]


 Dim Rollno As Integer
 Dim Empname As String
 Dim Salary As Double
 Dim Empid, Studid ,ABC,DEF As Integer
 Dim result_status As Boolean
 Static name As String
 Public bill As Decimal = 0
 Private xyz as integer
 Shared abc as String

E. Constant
 The constants refer to fixed values that the program may not alter during its execution.
 Constants can be of any of the basic data types like an integer constant, a floating constant, a character
constant, or a string literal. There are also enumeration constants as well.

Module abc
Sub Main()
Const PI = 3.14149
Dim radius, area As Integer
radius = 7
area = PI * radius * radius
Console.WriteLine("Area = " & CStr(area))
Console.ReadKey()
End Sub
End Module

List of Available Modifiers in VB.Net


The modifiers are keywords added with any programming element to give some especial emphasis on how the
programming element will behave or will be accessed in the program.

The following table provides the complete list of VB.Net modifiers −

Sr.No Modifier Description

1 Ansi Specifies that Visual Basic should marshal all strings to


American National Standards Institute (ANSI) values
regardless of the name of the external procedure being
declared.

2 Assembly Specifies that an attribute at the beginning of a source file


applies to the entire assembly.

3 Async Indicates that the method or lambda expression that it modifies


is asynchronous. Such methods are referred to as async
methods. The caller of an async method can resume its work
without waiting for the async method to finish.

4 Auto The charsetmodifier part in the Declare statement supplies the


character set information for marshaling strings during a call to
the external procedure. It also affects how Visual Basic
searches the external file for the external procedure name. The
Auto modifier specifies that Visual Basic should marshal strings
according to .NET Framework rules.
5 ByRef Specifies that an argument is passed by reference, i.e., the
called procedure can change the value of a variable underlying
the argument in the calling code. It is used under the contexts
of −

 Declare Statement
 Function Statement
 Sub Statement

6 ByVal Specifies that an argument is passed in such a way that the


called procedure or property cannot change the value of a
variable underlying the argument in the calling code. It is used
under the contexts of −

 Declare Statement
 Function Statement
 Operator Statement
 Property Statement
 Sub Statement

7 Default Identifies a property as the default property of its class,


structure, or interface.

8 Friend
Specifies that one or more declared programming elements
are accessible from within the assembly that contains their
declaration, not only by the component that declares them.
Friend access is often the preferred level for an application's
programming elements, and Friend is the default access level
of an interface, a module, a class, or a structure.

9 In It is used in generic interfaces and delegates.

10 Iterator Specifies that a function or Get accessor is an iterator. An


iterator performs a custom iteration over a collection.

11 Key The Key keyword enables you to specify behavior for


properties of anonymous types.

12 Module Specifies that an attribute at the beginning of a source file


applies to the current assembly module. It is not same as the
Module statement.

13 MustInherit Specifies that a class can be used only as a base class and
that you cannot create an object directly from it.

14 MustOverride Specifies that a property or procedure is not implemented in


this class and must be overridden in a derived class before it
can be used.

15 Narrowing Indicates that a conversion operator (CType) converts a class


or structure to a type that might not be able to hold some of the
possible values of the original class or structure.

16 NotInheritable Specifies that a class cannot be used as a base class.

17 NotOverridable Specifies that a property or procedure cannot be overridden in


a derived class.

18 Optional Specifies that a procedure argument can be omitted when the


procedure is called.

19 Out For generic type parameters, the Out keyword specifies that
the type is covariant.

20 Overloads Specifies that a property or procedure redeclares one or more


existing properties or procedures with the same name.

21 Overridable Specifies that a property or procedure can be overridden by an


identically named property or procedure in a derived class.

22 Overrides Specifies that a property or procedure overrides an identically


named property or procedure inherited from a base class.

23 ParamArray ParamArray allows you to pass an arbitrary number of


arguments to the procedure. A ParamArray parameter is
always declared using ByVal.

24 Partial Indicates that a class or structure declaration is a partial


definition of the class or structure.

25 Private Specifies that one or more declared programming elements are


accessible only from within their declaration context, including
from within any contained types.

26 Protected Specifies that one or more declared programming elements are


accessible only from within their own class or from a derived
class.

27 Public Specifies that one or more declared programming elements


have no access restrictions.

28 ReadOnly Specifies that a variable or property can be read but not written.

29 Shadows Specifies that a declared programming element redeclares and


hides an identically named element, or set of overloaded
elements, in a base class.

30 Shared Specifies that one or more declared programming elements are


associated with a class or structure at large, and not with a
specific instance of the class or structure.

31 Static Specifies that one or more declared local variables are to


continue to exist and retain their latest values after termination
of the procedure in which they are declared.

32 Unicode Specifies that Visual Basic should marshal all strings to


Unicode values regardless of the name of the external
procedure being declared.

33 Widening Indicates that a conversion operator (CType) converts a class


or structure to a type that can hold all possible values of the
original class or structure.

34 WithEvents Specifies that one or more declared member variables refer to


an instance of a class that can raise events.

35 WriteOnly Specifies that a property can be written but not read.


STATEMENTS:
A statement is a complete instruction in Visual Basic programs.
It may contain

 keywords, operators

 variables

 literal values

 constants and

 expressions.
Statements could be categorized as −

 Declaration statements
these are the statements where you name a variable, constant, or procedure, and can also specify a data
type.
 Executable statements
these are the statements, which initiate actions. These statements can call a method or function, loop or
branch through blocks of code or assign values or expression to a variable or constant. In the last case, it
is called an Assignment statement.

Declaration Statements
The declaration statements are used to name and define procedures, variables, properties, arrays, and constants.
When can programming element and also its data type, access level, and scope.
The programming elements you may declare include variables, constants, enumerations, classes, structures,
modules, interfaces, procedures, procedure parameters, function returns, external procedure references, operators,
properties, events, and delegates.
Following are the declaration statements in VB.Net −

Sr.No Statements and Description Example

1 Dim number As
Dim Statement Integer
Declares and allocates storage space for one or more Dim quantity As
Integer = 100
variables.
Dim message As
String = "Hello!"

2 Const maximum As
Const Statement Long = 1000
Declares and defines one or more constants. Const
naturalLogBase As
Object
=
CDec(2.7182818284)

3 Enum CoffeeMugSize
Enum Statement Jumbo
Declares an enumeration and defines the values of its ExtraLarge
Large
members.
Medium
Small
End Enum
4 Class Box
Class Statement Public length As
Declares the name of a class and introduces the definition Double
Public breadth As
of the variables, properties, events, and procedures that
Double
the class comprises. Public height As
Double
End Class

5 Structure Box
Structure Statement Public length As
Declares the name of a structure and introduces the Double
Public breadth As
definition of the variables, properties, events, and
Double
procedures that the structure comprises. Public height As
Double
End Structure

6 Public Module
Module Statement myModule
Declares the name of a module and introduces the Sub Main()
Dim user As String
definition of the variables, properties, events, and
=
procedures that the module comprises. InputBox("What is
your name?")
MsgBox("User name
is" & user)
End Sub
End Module

7 Public Interface
Interface Statement MyInterface
Declares the name of an interface and introduces the Sub
doSomething()
definitions of the members that the interface comprises.
End Interface

8 Function
Function Statement myFunction
Declares the name, parameters, and code that define a (ByVal n As
Integer) As Double
Function procedure.
Return 5.87 * n
End Function

9 Sub mySub(ByVal s
Sub Statement As String)
Declares the name, parameters, and code that define a Return
End Sub
Sub procedure.

10 Declare Function
Declare Statement getUserName
Declares a reference to a procedure implemented in an Lib "advapi32.dll"
Alias
external file.
"GetUserNameA"
(
ByVal lpBuffer
As String,
ByRef nSize As
Integer) As
Integer

11 Public Shared
Operator Statement Operator +
Declares the operator symbol, operands, and code that (ByVal x As obj,
define an operator procedure on a class or structure. ByVal y As obj) As
obj
Dim r As New
obj
' implemention
code for r = x + y
Return r
End Operator

12 ReadOnly Property
Property Statement quote() As String
Declares the name of a property, and the property Get
Return
procedures used to store and retrieve the value of the
quoteString
property. End Get
End Property

13 Public Event
Event Statement Finished()
Declares a user-defined event.

14 Delegate Function
Delegate Statement MathOperator(
Used to declare a delegate. ByVal x As
Double,
ByVal y As
Double
) As Double

Executable Statements
An executable statement performs an action. Statements calling a procedure, branching to another place in the
code, looping through several statements, or evaluating an expression are executable statements. Example

Module decisions
Sub Main()
Dim a As Integer = 10

If a < 20 Then
Console.WriteLine("a is less than 20")
End If
Console.WriteLine("value of a is : {0}", a)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
a is less than 20;
value of a is : 10
VB.Net Arrays: String, Dynamic

What is an Array?
An array is a data structure used to store elements of the same data type. The elements are ordered
sequentially with the first element being at index 0 and the last element at index n-1, where n is the
total number of elements in the array.

 Dim myData() As Integer


 Dim myData(10) As String
 Dim myData() As Integer = {11, 12, 22, 7, 47, 32}
 Dim students() As String = {"John", "Alice", "Antony", "Gloria", "jayden"}

 Fixed-Size Arrays:A fixed-size array holds a fixed number of elements. This means
that you must define the number of elements that it will hold during its definition. Suppose
you need an array to hold only 3 student names. You can define and initialize the array as
follows:

Dim students(2) As String


students(0) = "John"
students (1) = "Alice"
students (2) = "Antony"

 Dynamic Arrays

This is an array that can hold any number of elements. The array size can grow at any time. This
means that you can add new elements to the array any time we want. To demonstrate this, let us
first define an array of integers:

Dim nums() As Integer

We have defined an integer array named nums. You now need to add two elements to the array,
while giving room for resizing it. You need to use the ReDim statement as follows:

ReDim nums(1)
nums(0) = 12
nums(1) = 23

ReDim Preserve nums(2)


nums(2) = 35

Preserve is used to keep intact the old values in the

M---CA/IT done array.


th
here.date:-7 of October.
Module ranchi
Sub Main()
Dim students(2) As String
students(0) = "John"
students(1) = "Alice"
students(2) = "Antony"
Console.WriteLine("First student is" & students(0))
Console.WriteLine("Second student is {0} ", students(1))
Console.WriteLine("Third student is {0} ", students(2))
Console.ReadKey()
End Sub
End Module

Module ABC
Sub Main()
Dim n(10) As Integer
Dim i, j As Integer

For i = 0 To 10
n(i) = i + 100
Next i

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

Console.ReadKey()

End Sub
End Module
One Dimentional array
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 8
Console.WriteLine(i & vbTab & marks(i))
Next i

Console.ReadKey()
End Sub
End Module

Two dimentional array


Dim values(2,2) As String = New String(,) {{"AA", "BB",”XX”}, {"CC",
"DD",”XX”},{“EE”,”FF”,”XX”}}

Dim strBooks(4, 1) As String


strBooks (0, 0) = "John"
strBooks (0, 1) = "UMA"
strBooks (1, 0) = "Shalini"
strBooks (1, 1) = "Bill Gates"
strBooks (2, 0) = "Neha"
strBooks (2, 1) = "Saima”
strBooks (3, 0) = "Sanjay"
strBooks (3, 1) = "Abhishek"
strBooks (4, 0) = "Anushka"
strBooks (4, 1) = "Alan Woods"
For i = 0 To 8
Console.WriteLine(i & vbTab & marks(i))
Next i

For x = 0 To 4
For y = 0 To 1
Console.WriteLine (strBooks(x,y))
Next y
Next x
Three Dimentional Array
Module Ranchi
Sub Main()
Dim threeD(2, 4, 3) As Integer
threeD(0, 0, 0) = 1
threeD(0, 1, 0) = 2
threeD(0, 2, 0) = 3
threeD(0, 3, 0) = 4
threeD(0, 4, 0) = 5
threeD(1, 1, 1) = 2
threeD(2, 2, 2) = 3
threeD(2, 2, 3) = 4

For i As Integer = 0 To threeD.GetLength(2) - 1


For y As Integer = 0 To threeD.GetLength(1) - 1
For x As Integer = 0 To threeD.GetLength(0) - 1
Console.Write(threeD(x, y, i))
Next
Console.WriteLine()
Next
Console.WriteLine()
Next
End Sub
End Module

Module Module1
Sub Main()
Dim array(2) As Integer
array(0) = 100
array(1) = 10
array(2) = 1
For Each x As Integer In array
Console.WriteLine(x)
Next
End Sub
End Module

For Each element [ As datatype ] In group


[ statements ]
[ Continue For ]
[ statements ]
[ Exit For ]
[ statements ]
Next [ element ]
Element Required in the For Each statement. Optional in
the Next statement. Variable. Used to iterate through the
elements of the collection.
Statements Optional. One or more statements between For
Each and Next that run on each item in group.

Continue For Optional. Transfers control to the start of the For


Each loop.

Exit For Optional. Transfers control out of the For Each loop.
Next Required. Terminates the definition of the For Each loop.
Decision Making constructs

If ... Then An If...Then statement consists of a boolean expression


statement followed by one or more statements.

If...Then...Else An If...Then statement can be followed by an optional Else


statement statement, which executes when the boolean expression is
false.

If …elseif else

nested If You can use one If or Else if statement inside


statements another If or Else if statement(s).

Select Case A Select Case statement allows a variable to be tested for


statement equality against a list of values.

nested Select You can use one select case statement inside another select
Case statements case statement(s).

Examples:

If a < 20 Then
Console.WriteLine("a is less than 20")
End If

If count = 0 Then
message = "There are no items."
else
message = “There is one item”
End If

Dim totalMarks As Integer


totalMarks = 59
If totalMarks >= 80 Then
MsgBox("Gor Higher First Class ")
ElseIf totalMarks >= 60 Then
MsgBox("Gor First Class ")
ElseIf totalMarks >= 40 Then
MsgBox("Just pass only")
Else
MsgBox("Failed")
End If
Dim grade As Char
grade = "B"
Select grade
Case "A"
Console.WriteLine("Excellent!")
Case "B", "C"
Console.WriteLine("Well done")
Case "D"
Console.WriteLine("You passed")
Case "F"
Console.WriteLine("Better try again")
Case Else
Console.WriteLine("Invalid grade")
End Select
Console.WriteLine("Your grade is {0}", grade)
Console.ReadLine()
End Sub

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
For(a=1;a<=19;a++
executes.
For i=1 to 19 step 1

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.
Dim a As Integer = 10
Do
Console.WriteLine("value of a: {0}", a)
a = a + 1
Loop While (a < 20)

For a = 10 To 20
Console.WriteLine("value of a: {0}", a)
Next

For a = 10 To 20 Step 2
Console.WriteLine("value of a: {0}", a)
Next

Dim anArray() As Integer = {1, 3, 5, 7, 9}


Dim arrayItem As Integer
For Each arrayItem In anArray
Console.WriteLine(arrayItem)
Next

Dim a as integer=1
While a < 20
Console.WriteLine("value of a: {0}", a)
a = a + 1
End While

Dim aBook,bBook as new Book


With aBook
.Name = "VB.Net Programming1"
.Author = "Zara Ali1"
.Subject = "Information Technology1"
End With

With bBook
.Name = "Java"
.Author = "Zara Ali2"
.Subject = "Information Technology2"
End With
For i = 2 To 100
For j = 2 To i
If ((i Mod j) = 0) Then
Exit For
End If
Next j
If (j > (i \ j)) Then
Console.WriteLine("{0} is prime", i)
End If
Next i
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
Function/sub
Access_Specifier: It defines the access level of the function such as public, private, or friend, Protected function
to access the method.

o Function_Name: The function_name indicate the name of the function that should be unique.
o ParameterList: It defines the list of the parameters to send or retrieve data from a method.
o Return_Type: It defines the data type of the variable that returns by the function.

FUNCTION SIGNATURE

*WE CANNOT HAVE TWO OR MORE FUNCTION WITH THE SAME NAME AND PARAMETER SET.

*YOU CAN HAVE TWO FUNCTIONS WITH THE SAME NAME

*FUNCTION NAME + FUNCTION PARAMETER SET =FUNCTION SIGNATURE

* IS THE RETURN TYPE OF A FUNCTION A PART OF FUNCTION SIGNATURE.==>NO

PUBLIC Sub CalculatePay(hours As integer, wage As integer)


Dim pay As integer
pay = hours * wage
Console.WriteLine("Total Pay: {0: }", pay)
End Sub
definition

SUB MAIN(

CalculatePay(25, 10)
END SUB

Passing Parameters by Value


This is the default mechanism for passing parameters to a method. In this mechanism, when a method is called, a
new storage location is created for each value parameter. The values of the actual parameters are copied into them.
So, the changes made to the parameter inside the method have no effect on the argument.

Module paramByval
Sub swap(ByVal x As Integer, ByVal y As Integer)
Dim temp As Integer
temp = x
x = y
y = temp
End Sub

Sub Main()
Dim a As Integer = 100
Dim b As Integer = 200
Console.WriteLine("Before swap, value of a : {0}", a)
Console.WriteLine("Before swap, value of b : {0}", b)
' calling a function to swap the values '
swap(a, b)
Console.WriteLine("After swap, value of a : {0}", a)
Console.WriteLine("After swap, value of b : {0}", b)
Console.ReadLine()
End Sub
End Module
OUTPUT WOULD BE:

Before swap, value of a :100


Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
Passing Parameters by Reference
A reference parameter is a reference to a memory location of a variable. When you pass parameters by reference,
unlike value parameters, a new storage location is not created for these parameters. The reference parameters
represent the same memory location as the actual parameters that are supplied to the method.

Module paramByref
Sub swap(ByRef x As Integer, ByRef y As Integer)
Dim temp As Integer
temp = x ' save the value of x
x = y ' put y into x
y = temp 'put temp into y
End Sub

Sub Main()
' local variable definition
Dim a As Integer = 100
Dim b As Integer = 200
Console.WriteLine("Before swap, value of a : {0}", a)
Console.WriteLine("Before swap, value of b : {0}", b)
' calling a function to swap the values '
swap(a, b)
Console.WriteLine("After swap, value of a : {0}", a)
Console.WriteLine("After swap, value of b : {0}", b)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100

A procedure is a group of statements that together perform a task when called. After the procedure is executed, the
control returns to the statement calling the procedure. VB.Net has two types of procedures −

 Functions

 Sub procedures or Subs


Functions return a value, whereas Subs do not return a value.

Defining a Function
The Function statement is used to declare the name, parameter and the body of a function. The syntax for the
Function statement is −
[Modifiers] Function FunctionName [(ParameterList)] As ReturnType
[Statements]
End Function
Where,
 Modifiers /Access specifiers− specify the access level of the function; possible values are: Public, Private,
Protected, Friend, Protected Friend and information regarding overloading, overriding, sharing, and
shadowing.

 FunctionName − indicates the name of the function

 ParameterList − specifies the list of the parameters

 ReturnType − specifies the data type of the variable the function returns

Example
Following code snippet shows a function FindMax that takes two integer values and returns the larger of the two.

Function FindMax(ByVal num1 As Integer, ByVal num2 As Integer)


As Integer
' local variable declaration */
Dim result As Integer

If (num1 > num2) Then


result = num1
Else
result = num2
End If
RETURN result
End Function

Function Returning a Value


In VB.Net, a function can return a value to the calling code in two ways −

 By using the return statement

 By assigning the value to the function name


The following example demonstrates using the FindMax function −

Module myfunctions
Function FindMax(ByVal num1 As Integer, ByVal num2 As
Integer) As Integer
' local variable declaration */
Dim result As Integer

If (num1 > num2) Then


result = num1
Else
result = num2
End If
FindMax = result
End Function
Sub Main()
Dim a As Integer = 100
Dim b As Integer = 200
Dim res As Integer

res = FindMax(a, b)
Console.WriteLine("Max value is : {0}", res)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Max value is : 200

Recursive Function
A function can call itself. This is known as recursion. Following is an example that calculates factorial for a given
number using a recursive function −

Module myfunctions

Function factorial(ByVal num As Integer) As Integer


Dim result As Integer
If (num = 1) Then
Return 1
Else
result = factorial(num - 1) * num
Return result
End If
End Function

Sub Main()
'calling the factorial method
Console.WriteLine("Factorial of 6 is : {0}", factorial(6))
Console.WriteLine("Factorial of 7 is : {0}", factorial(7))
Console.WriteLine("Factorial of 8 is : {0}", factorial(8))
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Factorial of 6 is: 720
Factorial of 7 is: 5040
Factorial of 8 is: 40320

A procedure is a group of statements that together perform a task when called. After the procedure is executed, the
control returns to the statement calling the procedure. VB.Net has two types of procedures −

 Functions
 Sub procedures or Subs
Functions return a value, whereas Subs do not return a value.
Class
A class definition starts with the keyword Class followed by the class name; and the class body, ended by the End
Class statement.

 attributelist is a list of attributes that apply to the class. Optional.

 accessmodifier defines the access levels of the class, it has values as - Public, Protected, Friend,
Protected Friend and Private. Optional.

 Shadows indicate that the variable re-declares and hides an identically named element, or set of
overloaded elements, in a base class. Optional.

 MustInherit specifies that the class can be used only as a base class and that you cannot create an object
directly from it, i.e., an abstract class. Optional.

 NotInheritable specifies that the class cannot be used as a base class.

 Partial indicates a partial definition of the class.

 Inherits specifies the base class it is inheriting from.

Class b:public a
Class abc
Inherits def

 Implements specifies the interfaces the class is inheriting from.

Class abc
Inherits def
Implements imp1

The following example demonstrates a Box class, with three data members, length, breadth and height −

Module mybox

Class Box
Public length As Double ' Length of a box
Public breadth As Double ' Breadth of a box
Public height As Double ' Height of a box
End Class
Sub Main()
Dim Box1 As Box = New Box()
Dim Box2 As Box = New Box()

Dim volume As Double = 0.0


Box1.height = 5.0
Box1.length = 6.0
Box1.breadth = 7.0

Box2.height = 10.0
Box2.length = 12.0
Box2.breadth = 13.0

volume = Box1.height * Box1.length * Box1.breadth


Console.WriteLine("Volume of Box1 : {0}", volume)

volume = Box2.height * Box2.length * Box2.breadth


Console.WriteLine("Volume of Box2 : {0}", volume)

Console.ReadKey()

End Sub
End Module

When the above code is compiled and executed, it produces the following
result −
Volume of Box1 : 210
Volume of Box2 : 1560

Member Functions and Encapsulation


A member function of a class is a function that has its definition or its prototype within the class definition like any
other variable. It operates on any object of the class of which it is a member and has access to all the members of a
class for that object.
Member variables are attributes of an object (from design perspective) and they are kept private to implement
encapsulation. These variables can only be accessed using the public member functions.
Let us put above concepts to set and get the value of different class members in a class −

Module mybox
Class Box
Public length As Double ' Length of a box
Public breadth As Double ' Breadth of a box
Public height As Double ' Height of a box

Public Sub setLength(ByVal len As Double)


length = len
End Sub

Public Sub setBreadth(ByVal bre As Double)


breadth = bre
End Sub
Public Sub setHeight(ByVal hei As Double)
height = hei
End Sub

Public Function getVolume() As Double


Return length * breadth * height
End Function
End Class

Sub Main()
Dim Box1 As Box = New Box() ' Declare Box1 of type Box
Dim Box2 As Box = New Box() ' Declare Box2 of type Box
Dim volume As Double = 0.0 ' Store the volume of a
box here

' box 1 specification


Box1.setLength(6.0)
Box1.setBreadth(7.0)
Box1.setHeight(5.0)

'box 2 specification
Box2.setLength(12.0)
Box2.setBreadth(13.0)
Box2.setHeight(10.0)

' volume of box 1


volume = Box1.getVolume()
Console.WriteLine("Volume of Box1 : {0}", volume)

'volume of box 2
volume = Box2.getVolume()
Console.WriteLine("Volume of Box2 : {0}", volume)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Volume of Box1 : 210
Volume of Box2 : 1560
Constructors and Destructors
A class constructor is a special member Sub of a class that is executed whenever we create new
objects of that class. A constructor has the name New and it does not have any return type.

Following program explains the concept of constructor −

Class Line
Private length As Double

Public Sub New()


Console.WriteLine("Object is being created")
End Sub

Public Sub setLength(ByVal len As Double)


length = len
End Sub

Public Function getLength() As Double


Return length
End Function

Sub Main()
Dim ll As Line = New Line()
ll.setLength(6.0)
Console.WriteLine("Length of line : {0}", ll.getLength())
Console.ReadKey()
End Sub

End Class

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

Object is being created


Length of line : 6
A default constructor does not have any parameter, but if you need, a constructor can have
parameters. Such constructors are called parameterized constructors. This technique helps you to assign initial
value to an object at the time of its creation as shown in the following example −

Class Line
Private length As Double

Public Sub New(ByVal len As Double)


Console.WriteLine("Object is being created, length = {0}", len)
length = len
End Sub

Public Sub setLength(ByVal len As Double)


length = len
End Sub

Public Function getLength() As Double


Return length
End Function

Shared Sub Main()


Dim line As Line = New Line(10.0)
Console.WriteLine("Length of line set by constructor : {0}", line.getLength())
line.setLength(6.0)
Console.WriteLine("Length of line set by setLength : {0}", line.getLength())
Console.ReadKey()

End Sub
End Class

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

Object is being created, length = 10


Length of line set by constructor : 10
Length of line set by setLength : 6
A destructor is a special member Sub of a class that is executed whenever an object of its class goes out of scope.

A destructor has the name Finalize and it can neither return a value nor can it take any parameters.
Destructor can be very useful for releasing resources before coming out of the program like closing files, releasing
memories, etc.
Destructors cannot be inherited or overloaded.
Following example explains the concept of destructor

Class Line
Private length As Double ' Length of a line

Public Sub New()


Console.WriteLine("Object is being created")
End Sub

Protected Overrides Sub Finalize()


Console.WriteLine("Object is being deleted")
End Sub

Public Sub setLength(ByVal len As Double)


length = len
End Sub

Public Function getLength() As Double


Return length
End Function

Shared Sub Main()


Dim ll As Line = New Line()
'set line length
ll.setLength(6.0)
Console.WriteLine("Length of line : {0}", ll.getLength())
Console.ReadKey()
End Sub
End Class

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

Object is being created


Length of line : 6
Object is being deleted
Shared Members of a VB.Net Class
We can define class members as static using the Shared keyword. When we declare a member of a class as
Shared, it means no matter how many objects of the class are created, there is only one copy of the member.
The keyword Shared implies that only one instance of the member exists for a class. Shared variables are used for
defining constants because their values can be retrieved by invoking the class without creating an instance of it.
Shared variables can be initialized outside the member function or class definition. You can also initialize Shared
variables inside the class definition.
You can also declare a member function as Shared. Such functions can access only Shared variables. The Shared
functions exist even before the object is created.
The following example demonstrates the use of shared members −

Class StaticVar

Public Shared num As Integer

Public Sub count()


num = num + 1
End Sub

Public Shared Function getNum() As Integer


Return num
End Function

Shared Sub Main()


Dim s1,s2,s3 As StaticVar
S1= New StaticVar()
S2= New StaticVar()
S3=New StaticVar()

S1.count()
S2.count()
S3.count()
Console.WriteLine("Value of variable num: {0}", StaticVar.getNum())
Console.ReadKey()
End Sub

End Class

When the above code is compiled and executed, it produces the following result −
Inheritance
One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to
define a class in terms of another class which makes it easier to create and maintain an application. This also
provides an opportunity to reuse the code functionality and fast implementation time.
When creating a class, instead of writing completely new data members and member functions, the programmer
can designate that the new class should inherit the members of an existing class. This existing class is called
the base class, and the new class is referred to as the derived class.

Base & Derived Classes


A class can be derived from more than one class or interface, which means that it can inherit data and functions
from multiple base classes or interfaces.
The syntax used in VB.Net for creating derived classes is as follows −
<access-specifier> Class <base_class>
...
End Class
Class <derived_class>: Inherits <base_class>
...
End Class
Consider a base class Shape and its derived class Rectangle −

Class Shape
Protected width As Integer
Protected height As Integer

Public Sub setWidth(ByVal w As Integer)


width = w
End Sub

Public Sub setHeight(ByVal h As Integer)


height = h
End Sub
End Class

Class Rectangle
Inherits Shape
Public Function getArea() As Integer
Return (width * height)
End Function
End Class

Class RectangleTester
Shared Sub Main()
Dim rect As Rectangle = New Rectangle()
rect.setWidth(5)
rect.setHeight(7)
Console.WriteLine("Total area: {0}", rect.getArea())
Console.ReadKey()
End Sub
End Class

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

Total area: 35

Base Class Initialization


The derived class inherits the base class member variables and member methods. Therefore, the super class object
should be created before the subclass is created. The super class or the base class is implicitly known
as MyBase in VB.Net

The following program demonstrates this −

Class Rectangle
Protected width As Double
Protected length As Double

Public Sub New(ByVal l As Double, ByVal w As Double)


length = l
width = w
End Sub

Public Function GetArea() As Double


Return (width * length)
End Function

Public Overridable Sub Display()


Console.WriteLine("Length: {0}", length)
Console.WriteLine("Width: {0}", width)
Console.WriteLine("Area: {0}", GetArea())
End Sub

End Class

Class Tabletop

Inherits Rectangle
Private cost As Double

Public Sub New(ByVal l As Double, ByVal w As Double)

MyBase.New(l, w)
End Sub

Public Function GetCost() As Double


Dim cost As Double
cost = GetArea() * 70
Return cost
End Function

Public Overrides Sub Display()


MyBase.Display()
Console.WriteLine("Cost: {0}", GetCost())
End Sub
End Class

Class RectangleTester
Shared Sub Main()
Dim t As Tabletop = New Tabletop(4.5, 7.5)
t.Display()
Console.ReadKey()
End Sub
End Class

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

Length: 4.5
Width: 7.5
Area: 33.75
Cost: 2362.5
By default, all classes are inheritable unless marked with the NotInheritable keyword. Classes can inherit from other
classes in your project or from classes in other assemblies that your project references

class-level statements and modifiers to support inheritance:

 Inherits statement CLASS-WE CAN MAKE ITS OBJECT AND WE CAN ALSO INHERIT FROM THERE./AUTO
 NotInheritable modifier WE CANNOT INHERIT FROM THERE BUT CAN MAKE OBJECT OF IT.
 MustInherit modifier WE FOR SURE HAVE TO INHERIT FROM THERE BUT WE CANT MAKE ITS OBJECT.

Must Inherit Example

Animal might be a good example of MustInherit. Dog would be a class that might be derived from Animal, and is not
marked with MustInherit. The developer can create a new instance of Dog, but not of Animal. MustOverride is a
method that a derived class must provide an implementation for.

MustInherit means your Class is abstract and cannot be instantiated. Such classes
can only be instantiated indirectly, that is, you Inherit a Class from them which
implements the not implemented methods and instantiate that child Class.

MustOverride means your method is not implemented and should be implemented in the
first non-abstract descendant class (the latest point to do that).

Module module1
Public MustInherit Class Xyz
Public MustOverride function abc() As String
End Class

Public Class ZZZ


Inherits Xyz
Public Overrides function abc() As String
Console.writeline(“This is the overridden function from the derived
class”)
End Function
END CLASS

Sub main()
Dim z as new ZZZ()
z.abc()
End sub
End MODULE
NOTINHERITABLE-----FINAL CLASS

Specifies that a class cannot be used as a base class.


A class that cannot be inherited is sometimes called a sealed/FINAL class.

NOTINHERITABLE CLASS ABC


SUB A1()
CONSOLE.WRITELINE(“HELLO”)
END SUB
END CLASS
Overriding Properties and Methods in Derived
Classes
 Overridable override karo to thik nahi karo to bhi OK
 Overrides Child class main rewrite karna method ko
 NotOverridable Child class main override nahi kar sakte
 MustOverride Child class main Override karna hi padega
Overridable example:

Public Class Users


Public Overridable Sub
GetInfo()

Console.WriteLine("Base
Class")
End Sub
End Class

Public Class Details


Inherits Users

Public Overrides Sub GetInf


o()
Mybase.GetInfo()
Console.WriteLine("Derived
Class")
End Sub
End Class

Class xyz
Sub main()
Dim dd as Detail()
dd= new Details()
dd.GetInfo()
end sub
end class
MustInherit Public Class Public Class Button
Control Inherits Control
Public Sub New(top As Public Sub New(top As
Integer, left As Integer) Integer, left As Integer)
Me.top = top MyBase.New(top, left)
Me.left = left End Sub
End Sub Public Overrides Sub
DrawControl( )
Public MustOverride Sub Console.WriteLine("Drawing a
DrawControl( ) button at {0}, {1}" +
Protected top As Integer ControlChars.Lf, top, left)
Protected left As Integer End Sub
End Class End Class

Public Class Label Public Class Tester


Inherits Control Shared Sub Main()
Dim winArray(3) As Control
Private listBoxContents As winArray(0) = New Label(1, 2,
String "A")
winArray(1) = New Label(3, 4,
Public Sub New(top As "B")
Integer, left As Integer, winArray(2) = New Button(5,
contents As String) 6)
MyBase.New(top, left)
listBoxContents = contents Dim i As Integer
End Sub For i = 0 To 2
Public Overrides Sub
DrawControl( ) winArray(i).DrawControl( )
Console.WriteLine("Writing Next i
string to the listbox: {0}", End Sub 'Main
listBoxContents) End Class 'Tester
End Sub
End Class
Optional. Can be one of the following:
access
modifier
- Public
declared programming elements have no
access restrictions.

Declaration Context. You can use Public only


at module, interface, or namespace level. This
means the declaration context for a Public
element must be a source file, namespace,
interface, module, class, or structure, and cannot
be a procedure.

- Protected
specifies that one or more declared
programming elements are accessible only
from within their own class or from a derived
class.

Declaration Context. You can use


Protected only at the class level. This
means the declaration context for a
Protected element must be a class, and
cannot be a source file, namespace, interface,
module, structure, or procedure.
- Friend
Friend access is often the preferred level for
an application's programming elements, and
Friend is the default access level of an
interface, a module, a class, or a structure.

- Private
elements are accessible only from within their
declaration context, including from within
any contained types.

Declaration Context. You can use


Private only at module level. This means
the declaration context for a Private
element must be a module, class, or
structure, and cannot be a source file,
namespace, interface, or procedure.

- Protected Friend
The Protected Friend keyword combination is a member access
modifier. It confers both Friend access and Protected access on
the declared elements, so they are accessible from anywhere in
the same assembly, from their own class, and from derived classes.
You can specify Protected Friend only on members of classes;
you cannot apply Protected Friend to members of a structure
because structures cannot be inherited.

Declaration Context. You can use Protected Friend only at


the class level. This means the declaration context for a
Protected element must be a class, and cannot be a source file,
namespace, interface, module, structure, or procedure.

- Private Protected
The Private Protected keyword combination is a member access
modifier. A Private Protected member is accessible by all members
in its containing class, as well as by types derived from the
containing class, but only if they are found in its containing
assembly.

You can specify Private Protected only on members of classes; you


cannot apply Private Protected to members of a structure because
structures cannot be inherited.

sFixedSize
Gets a value indicating whether
the Array has a fixed size.

2 IsReadOnly
Gets a value indicating whether the Array
only.
3 Length
Gets a 32-bit integer that represents the tota
of elements in all the dimensions of the Array

4 LongLength
Gets a 64-bit integer that represents the tota
of elements in all the dimensions of the Array

5 Rank
Gets the rank (number of dimensions) of the

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

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


Integer)
Sets a range of elements in the Array to zero, to false, or to null, depe
the element type.

2 Public Shared Sub Copy (sourceArray As Array, destinationArray A


length As Integer)
Copies a range of elements from an Array starting at the first element an
them into another Array starting at the first element. The length is speci
32-bit integer.
3 Public Sub CopyTo (array As Array, index As Integer)
Copies all the elements of the current one-dimensional Array to the speci
dimensional Array starting at the specified destination Array index. The
specified as a 32-bit integer.

4 Public Function GetLength (dimension As Integer) As Integer


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

5 Public Function GetLongLength (dimension As Integer) As Long


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

6 Public Function GetLowerBound (dimension As Integer) As Integer


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

7 Public Function GetType As Type


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

8 Public Function GetUpperBound (dimension As Integer) As Integer


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

9 Public Function GetValue (index As Integer) As Object


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

10 Public Shared Function IndexOf (array As Array,value As Object) As


Searches for the specified object and returns the index of the first oc
within the entire one-dimensional Array.

11 Public Shared Sub Reverse (array As Array)


Reverses the sequence of the elements in the entire one-dimensional Arr

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


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

13 Public Shared Sub Sort (array As Array)


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

14 Public Overridable Function ToString As String


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:
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

KeyValuePair. A KeyValuePair is a Structure. It has two fields of specified


types. It stores two pieces of data together as a single object. In VB.NET it is
useful. It defines a Structure of any kind of key, and any kind of value
An associative array links a set of keys to a set of values. In Visual
Basic, associative arrays are implemented as Dictionaries. This
code produces a message box saying "Nevada."
Exception

An exception is a problem that arises during the execution of a


program. An exception is a response to an exceptional circumstance
that arises while a program is running,

System.systemException

Exception

Microsoft.Build.BuildEngine.InternalLoggerException
Microsoft.Build.BuildEngine.InvalidProjectFileException
Microsoft.Build.BuildEngine.InvalidToolsetDefinitionException
Microsoft.Build.BuildEngine.RemoteErrorException
Microsoft.Build.Exceptions.BuildAbortedException
Microsoft.Build.Exceptions.InternalLoggerException
Microsoft.Build.Exceptions.InvalidProjectFileException
Microsoft.Build.Exceptions.InvalidToolsetDefinitionException
Microsoft.Build.Framework.LoggerException
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
Microsoft.CSharp.RuntimeBinder.RuntimeBinderInternalCompilerException
Microsoft.Extensions.CommandLineUtils.CommandParsingException
Microsoft.Extensions.Options.OptionsValidationException
Microsoft.JScript.CmdLineException
Microsoft.JScript.ParserException
Microsoft.VisualBasic.ApplicationServices.CantStartSingleInstanceException
Microsoft.VisualBasic.ApplicationServices.NoStartupFormException
Microsoft.VisualBasic.Compatibility.VB6.WebClassContainingClassNotOptional
Microsoft.VisualBasic.Compatibility.VB6.WebClassCouldNotFindEvent
Microsoft.VisualBasic.Compatibility.VB6.WebClassNextItemCannotBeCurrentW
ebItem
Microsoft.VisualBasic.Compatibility.VB6.WebClassNextItemRespondNotFound
Microsoft.VisualBasic.Compatibility.VB6.WebClassUserWebClassNameNotOptio
nal
Microsoft.VisualBasic.Compatibility.VB6.WebClassWebClassFileNameNotOption
al
Microsoft.VisualBasic.Compatibility.VB6.WebClassWebItemNotValid
Microsoft.VisualBasic.Compatibility.VB6.WebItemAssociatedWebClassNotOptio
nal
Microsoft.VisualBasic.Compatibility.VB6.WebItemClosingTagNotFound
Microsoft.VisualBasic.Compatibility.VB6.WebItemCouldNotLoadEmbeddedReso
urce
Microsoft.VisualBasic.Compatibility.VB6.WebItemCouldNotLoadTemplateFile
Microsoft.VisualBasic.Compatibility.VB6.WebItemNameNotOptional
Microsoft.VisualBasic.Compatibility.VB6.WebItemNoTemplateSpecified
Microsoft.VisualBasic.Compatibility.VB6.WebItemTooManyNestedTags
Microsoft.VisualBasic.Compatibility.VB6.WebItemUnexpectedErrorReadingTem
plateFile
Microsoft.VisualBasic.CompilerServices.IncompleteInitialization
Microsoft.VisualBasic.CompilerServices.InternalErrorException
Microsoft.VisualBasic.FileIO.MalformedLineException
Mono.Security.Interface.TlsException
System.AggregateException
System.ApplicationException
System.InvalidTimeZoneException
System.SystemException
System.TimeZoneNotFoundException
System.Activities.InvalidWorkflowException
System.Activities.VersionMismatchException
System.Activities.WorkflowApplicationException
System.Activities.DynamicUpdate.InstanceUpdateException
System.Activities.ExpressionParser.SourceExpressionException
System.Activities.Expressions.LambdaSerializationException
System.Activities.Presentation.Metadata.AttributeTableValidationException
System.Activities.Statements.WorkflowTerminatedException
System.AddIn.Hosting.AddInSegmentDirectoryNotFoundException
System.AddIn.Hosting.InvalidPipelineStoreException
System.ComponentModel.Composition.CompositionContractMismatchExceptio
n
System.ComponentModel.Composition.CompositionException
System.ComponentModel.Composition.ImportCardinalityMismatchException
System.ComponentModel.Composition.Primitives.ComposablePartException
System.ComponentModel.DataAnnotations.ValidationException
System.ComponentModel.Design.ExceptionCollection
System.Composition.Hosting.CompositionFailedException
System.Configuration.SettingsPropertyIsReadOnlyException
System.Configuration.SettingsPropertyNotFoundException
System.Configuration.SettingsPropertyWrongTypeException
System.Configuration.Provider.ProviderException
System.Data.Linq.ChangeConflictException
System.Diagnostics.Eventing.Reader.EventLogException
System.Diagnostics.Tracing.EventSourceException
System.DirectoryServices.ActiveDirectory.ActiveDirectoryObjectExistsException
System.DirectoryServices.ActiveDirectory.ActiveDirectoryObjectNotFoundExcep
tion
System.DirectoryServices.ActiveDirectory.ActiveDirectoryOperationException
System.DirectoryServices.ActiveDirectory.ActiveDirectoryServerDownException
System.DirectoryServices.Protocols.DirectoryException
System.Formats.Asn1.AsnContentException
System.Formats.Cbor.CborContentException
System.IdentityModel.AsynchronousOperationException
System.IdentityModel.RequestException
System.IdentityModel.Metadata.MetadataSerializationException
System.IdentityModel.Protocols.WSTrust.WSTrustSerializationException
System.IdentityModel.Selectors.CardSpaceException
System.IdentityModel.Selectors.IdentityValidationException
System.IdentityModel.Selectors.PolicyValidationException
System.IdentityModel.Selectors.ServiceBusyException
System.IdentityModel.Selectors.ServiceNotStartedException
System.IdentityModel.Selectors.StsCommunicationException
System.IdentityModel.Selectors.UnsupportedPolicyOptionsException
System.IdentityModel.Selectors.UntrustedRecipientException
System.IdentityModel.Selectors.UserCancellationException
System.IdentityModel.Services.AsynchronousOperationException
System.IdentityModel.Services.FederatedAuthenticationSessionEndingExceptio
n
System.IdentityModel.Services.FederationException
System.IdentityModel.Services.WSFederationMessageException
System.IO.IsolatedStorage.IsolatedStorageException
System.IO.Log.SequenceFullException
System.Management.Instrumentation.InstrumentationBaseException
System.Management.Instrumentation.WmiProviderInstallationException
System.Net.Http.HttpRequestException
System.Net.Mail.SmtpException
System.Net.PeerToPeer.PeerToPeerException
System.Reflection.Metadata.ImageFormatLimitationException
System.Runtime.AmbiguousImplementationException
System.Runtime.CompilerServices.RuntimeWrappedException
System.Runtime.DurableInstancing.InstancePersistenceException
System.Runtime.Remoting.MetadataServices.SUDSGeneratorException
System.Runtime.Remoting.MetadataServices.SUDSParserException
System.Runtime.Serialization.InvalidDataContractException
System.Security.RightsManagement.RightsManagementException
System.ServiceModel.CommunicationException
System.ServiceModel.InvalidMessageContractException
System.ServiceModel.QuotaExceededException
System.ServiceModel.Channels.InvalidChannelBindingException
System.Text.Json.JsonException
System.Threading.BarrierPostPhaseException
System.Threading.LockRecursionException
System.Threading.Tasks.TaskSchedulerException
System.Web.Query.Dynamic.ParseException
System.Web.Security.MembershipCreateUserException
System.Web.Security.MembershipPasswordException
System.Web.UI.ViewStateException
System.Web.UI.WebControls.EntityDataSourceValidationException
System.Web.UI.WebControls.LinqDataSourceValidationException
System.Windows.Automation.NoClickablePointException
System.Windows.Automation.ProxyAssemblyNotLoadedException
System.Windows.Controls.PrintDialogException
System.Windows.Forms.AxHost.InvalidActiveXStateException
System.Windows.Xps.XpsException
System.Windows.Xps.XpsWriterException
System.Workflow.Activities.Rules.RuleException
System.Workflow.ComponentModel.WorkflowTerminatedException
System.Workflow.ComponentModel.Compiler.WorkflowValidationFailedExcepti
on
System.Workflow.ComponentModel.Serialization.WorkflowMarkupSerialization
Exception
System.Workflow.Runtime.WorkflowOwnershipException
System.Xaml.XamlException
Windows.UI.Xaml.LayoutCycleException
Windows.UI.Xaml.Automation.ElementNotAvailableException
Windows.UI.Xaml.Automation.ElementNotEnabledException
Windows.UI.Xaml.Markup.XamlParseException
Exception Condition

ArgumentException A non-null argument that is passed to a method is invalid.

ArgumentNullException An argument that is passed to a method is null.

ArgumentOutOfRangeException An argument is outside the range of valid values.

DirectoryNotFoundException Part of a directory path is not valid.

DivideByZeroException The denominator in an integer or Decimal division operation is zero.

DriveNotFoundException A drive is unavailable or does not exist.

FileNotFoundException A file does not exist.

FormatException A value is not in an appropriate format to be converted from a string by a conv


as Parse.

IndexOutOfRangeException An index is outside the bounds of an array or collection.

InvalidOperationException A method call is invalid in an object's current state.

KeyNotFoundException The specified key for accessing a member in a collection cannot be found.

NotImplementedException A method or operation is not implemented.

NotSupportedException A method or operation is not supported.

ObjectDisposedException An operation is performed on an object that has been disposed.

OverflowException An arithmetic, casting, or conversion operation results in an overflow.

PathTooLongException A path or file name exceeds the maximum system-defined length.

PlatformNotSupportedException The operation is not supported on the current platform.

RankException An array with the wrong number of dimensions is passed to a method.

TimeoutException The time interval allotted to an operation has expired.


Exception Condition

UriFormatException An invalid Uniform Resource Identifier (URI) is used.

1.System.SystemException
2.System.ApplicationException
Unstructured Exception Handling/Not OOPS base

On error Go to

Structured Exception Handling/OOPS based

Try

throw

Catch

End try

Exit try

Catch

catch

Finally
Handling these exceptions:

Try Optional. Statement(s) where an error can occur. Can be a compound statement.

Catch Optional. Multiple Catch blocks permitted. If an exception occurs when processing
the Try block, each Catch statement is examined in textual order to determine whether
handles the exception, with exception representing the exception that has been thrown

Exception Optional. Any variable name. The initial value of exception is the value of the thrown er
with Catch to specify the error caught. If omitted, the Catch statement catches any exce
Type Optional. Specifies the type of class filter. If the value of exception is of the type specifie
by type or of a derived type, the identifier becomes bound to the exception object.
When Optional. A Catch statement with a When clause catches exceptions only
when expression evaluates to True. A When clause is applied only after checking the typ
exception, and expression may refer to the identifier representing the exception.
Expression Optional. Must be implicitly convertible to Boolean. Any expression that describes a gen
filter. Typically used to filter by error number. Used with When keyword to specify circum
under which the error is caught.
Catch Optional. Statement(s) to handle errors that occur in the associated Try block. Can be a
compound statement.
Exit Try Optional. Keyword that breaks out of the Try...Catch...Finally structure. Execution re
with the code immediately following the End Try statement. The Finally statement will
executed. Not allowed in Finally blocks.
Finally Optional. A Finally block is always executed when execution leaves any part of
the Try...Catch statement.
finallyStatements Optional. Statement(s) that are executed after all other error processing has occurred.
End Try Terminates the Try...Catch...Finally structure.
System Exception
Application Exception

Examples:
Module Try_catch
Sub Main(ByVal args As String())
Dim strName As String = Nothing
Try
If strName.Length > 0 Then
Console.WriteLine(" Name of String is {0}", strName)
End If
Catch ex As Exception
Console.WriteLine(" Catch exception in a proram {0}"
, ex.Message)
End Try
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Module
Module TryException
Sub abc()
Try
Throw new DividebyzeroException
Catch b as exception
Console.writeline(“Exception occurred”)

Catch a as NumericException
Console.writeline(“Numeric Exception”)
Catch ex As DivideByZeroException
Console.WriteLine(" These exceptions were found i
n the program {0}", ex)
Finally
Console.WriteLine(" Division result “)
End Try
End Sub
Sub Main()
abc()
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Module
Module exceptionProg

Application exception thrown.

Sub Main()
Try
Throw New ApplicationException("A custom
exception _ is being thrown here...")
Catch e As Exception
Console.WriteLine(e.Message)
Finally
Console.WriteLine("Now inside the Finally
Block")
End Try
Console.ReadKey()
End Sub
End Module
Module exceptionProg

Public Class TempIsZeroException


Inherits ApplicationException

Public Sub New(ByVal message As String)


MyBase.New(message)
End Sub
End Class

Public Class Temperature


Dim temperature As Integer = 0
Sub showTemp()
If (temperature = 0) Then
Throw (New TempIsZeroException("Zero Temperature
found"))
Else
Console.WriteLine("Temperature: {0}", temperature)
End If
End Sub
End Class

Sub Main()
Dim temp As Temperature = New Temperature()
Try
temp.showTemp()
Catch e As TempIsZeroException
Console.WriteLine("TempIsZeroException: {0}", e.Message)
End Try
Console.ReadKey()
End Sub
End Module
Some more examples of creating an application exception sub class and
then firing it from the program logic.

1.

Public Class EmployeeListNotFoundException


Inherits Exception

Public Sub New()


End Sub

Public Sub New(message As String)


MyBase.New(message)
End Sub

Public Sub New(message As String, inner As Exception)


MyBase.New(message, inner)
End Sub
End Class
2.

Module Module1
Public Class HeightIsZeroException : Inherits
ApplicationException
Public Sub New(ByVal text As String)
MyBase.New(text)
End Sub
End Class
Public Class Height
Dim height As Integer = 0
Sub showHeight()
If (height = 0) Then
Throw (New HeightIsZeroException("Zero Height
found"))
Else
Console.WriteLine("Height is: {0}", height)
End If
End Sub
End Class
Sub Main()
Dim hght As Height = New Height()
Try
hght.showHeight()
Catch ex As HeightIsZeroException
Console.WriteLine("HeightIsZeroException: {0}",
ex.Message)
End Try
Console.ReadKey()
End Sub
End Module
Unstructured Exception Handling.

The parts of this statement are as follows:


 ON ERROR
 GoTo line
Calls the error-handling code that starts at
the line specified at line. Here, line is a line
label or a line number. If a runtime error
occurs, program execution goes to the
given location. The specified line must be in
the same procedure as the On
Error statement.

 GoTo 0
Disables the enabled error handler in the
current procedure.

 GoTo -1
Same as GoTo 0.

 Resume Next
Specifies that when an exception occurs,
execution skips over the statement that
caused the problem and goes to the
statement immediately following.
Execution continues from that point.
The following example shows how to use the On Error GoTo statement that
uses division by zero to create an overflow error. In this case, the code
redirects execution to the label Handler. You can create this label by
placing it on a line of its own followed by a colon:

1.
Module Module1

Sub Main()
On Error GoTo Handler
Exit Sub
Handler:
End Sub
End Module
2.
Error Number and Description
Module Module1
Sub Main()
On Error GoTo abc
Dim intItem1 As Integer = 0
Dim intItem2 As Integer = 128
Dim intResult As Integer
intResult = intItem2 / intItem1
Console.WriteLine("Press Enter to continue...")
Console.ReadLine()
Exit Sub
abc:
If (Err.Number = 6) Then
Console.WriteLine("An overflow error occurred.")
End If
Console.WriteLine("Press Enter to continue...")
Console.ReadLine()
End Sub
End Module

Err Object
3.

Note that we've used an Exit Sub statement here so that in normal execution, the procedure
stops before reaching the error-handling code that follows the Handler label. Now we can add
the code that causes the overflow error:

Module Module1
Sub Main()
On Error GoTo Handler
Dim intItem1 As Integer = 0
Dim intItem2 As Integer = 128
Dim intResult As Integer
intResult = intItem2 / intItem1
Console.WriteLine("Press Enter to continue...")
Console.ReadLine()
Exit Sub
Handler:
Console.writeline(“But this will never be reached”
End Sub
End Module

EXIT SUB
4.

Module Module1
Sub Main()
Dim int1 = 0, int2 = 1, int3 As Integer
On Error Goto Handler
int3 = int2 / int1
Exit Sub
Handler:
If (Err.Number = 6) Then
System.Console.WriteLine("Overflow error!")
End If
End Sub
End Module

Err Object
Err.Number property
5.
Module Module1
Sub Main()
Dim int1 = 0, int2 = 1, int3 As Integer
On Error Goto Handler
int3 = int2 / int1
Exit Sub
Handler:
If (TypeOf Err.GetException() Is OverflowException) Then
System.Console.WriteLine("Overflow error!")
End If
End Sub
End Module

Err.GetException()
Typeof

You might also like