Visual Basic NXT
Visual Basic NXT
user
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.
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
Module Abc
Sub Main()
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
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 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.
You can compile a VB.Net program by using the command line instead of the Visual Studio IDE –
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.
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.
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 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 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
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
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
'volume of box 1
volume = Box1.height * Box1.length * Box1.breadth
End Module
End Class
Interface-
End Interface
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:
Byte: allocated storage space of 1 byte. Values range from 0 to 255 (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.
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.
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.
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
Declare Statement
Function Statement
Sub Statement
Declare Statement
Function Statement
Operator Statement
Property Statement
Sub Statement
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.
13 MustInherit Specifies that a class can be used only as a base class and
that you cannot create an object directly from it.
19 Out For generic type parameters, the Out keyword specifies that
the type is covariant.
28 ReadOnly Specifies that a variable or property can be read but not written.
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 −
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.
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:
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:
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
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
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
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
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 …elseif else
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
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 a as integer=1
While a < 20
Console.WriteLine("value of a: {0}", a)
a = a + 1
End While
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.
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.
SUB MAIN(
CalculatePay(25, 10)
END SUB
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:
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
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.
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.
Module myfunctions
Function FindMax(ByVal num1 As Integer, ByVal num2 As
Integer) As Integer
' local variable declaration */
Dim result 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
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.
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.
Class b:public a
Class abc
Inherits def
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()
Box2.height = 10.0
Box2.length = 12.0
Box2.breadth = 13.0
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
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
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 2 specification
Box2.setLength(12.0)
Box2.setBreadth(13.0)
Box2.setHeight(10.0)
'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.
Class Line
Private length As Double
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 −
Class Line
Private length As Double
End Sub
End Class
When the above code is compiled and executed, it produces the following result −
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
When the above code is compiled and executed, it produces the following result −
Class 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.
Class Shape
Protected width As Integer
Protected height As Integer
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
Class Rectangle
Protected width As Double
Protected length As Double
End Class
Class Tabletop
Inherits Rectangle
Private cost As Double
MyBase.New(l, w)
End Sub
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
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.
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
Sub main()
Dim z as new ZZZ()
z.abc()
End sub
End MODULE
NOTINHERITABLE-----FINAL CLASS
Console.WriteLine("Base
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
- Protected
specifies that one or more declared
programming elements are accessible only
from within their own class or from a derived
class.
- Private
elements are accessible only from within their
declaration context, including from within
any contained types.
- 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.
- 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.
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
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
KeyNotFoundException The specified key for accessing a member in a collection cannot be found.
1.System.SystemException
2.System.ApplicationException
Unstructured Exception Handling/Not OOPS base
On error Go to
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
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
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.
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.
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