VB.NET
VB.NET
NET
IDE Level
.NET Framework
known as managed code, meaning that any dependencies your application might have are always
met and never broken.
Base Class Library
BCL is the portion of.NET Framework that defines all the basic data types, such as
System.Object (the root of the .NET object hierarchy), numeric and date types, string types,
arrays, and collections. It also contains classes for managing .NET core features such as file I/O,
threading, serialization, and security.
Data and XML layer
This layer contains the .NET classes that work with databases and with XML. XML is the format
that .NET uses to store virtually any kind of information. All the .NET configuration files are
based on XML. The Data portion – commonly called ADO.NET – is the .NET counterpart for
the ActiveX Data Objects (ADO) technology. ADO.NET focuses mainly on disconnected result-
sets called DataSets that store data coming from multiple tables, in the same database or different
databases.
ASP.NET/ Web Services and Windows Forms/ User Interfaces
The ASP.NET contain all the classes that can generate the user interface in a browser, while
Windows forms contain all classes that can generate user interface using the standard Win32
windows. ASP.NET comprises both Web Forms and Web services. Web Forms run on the server
and produce HTML code that is rendered in a browser on the client while Windows Forms run
on client’s Windows machine.
Common Language Specification
CLS is a set of specifications that Microsoft has supplied to help compiler vendors. These
specifications dictate minimum group of features that a .NET language must have, such as
support for signed integers of 16, 32 or 64 bits, zero-bound arrays, and structured exception
handling.
CLS compliant Programming languages
At the top of the figure are programming languages that comply with CLS (they meet the
minimum group of features that a .NET language must have). All these languages produce
managed code, which is code that runs under the control of the runtime. Managed code is quite
different from native code produced by traditional compilers, which is now referred to as
unmanaged code.
1.2 VB.NET compilation process
A VB.NET application is wrapped up in an assembly. An assembly includes all the information
you need about your application. It includes information that you would find currently in a type
library as well as information you need to use for the application or component. This makes your
application or component completely self-describing. When a VB.NET application is complied,
it is converted to an intermediate language called Microsoft Intermediate Language (MSIL). It is
then converted to machine code by CLR’s Just-In-Time (JIT) compiler. The MSIL allows an
application to run on any platform that supports CLR without changing the development code.
1.3 VB.NET Basics and Definitions
Modules
Modules are used to hold code that is outside of any class definition. Global variables, global
constants, and procedure libraries are often placed in standard modules. They also define
datatypes that cannot be instantiated and whose members are all static. The module block is
delimited by the Module and End Module keywords and can contain any number of variables,
subs, and functions.
Classes
A class is a template from which objects are made. It is a data structure that can contain data
members such as constants, variables, events and functions as methods and properties. Properties
and methods inside a class are called class members. It is delimited by Class…End Class
keyword. For example, consider class Student whose members are admno, firstname, and
YearofBirth as fields (properties) and calculate_age (ByVal current_year as integer, ByVal
YearofBirth as Long) as a member function. This would be defined as follows:
Class Student
'fields (properties)
'member function
Return age
End Function
End Class
Objects
An object is an instance of a class. It is an entity that contains both data members and methods. It
is defined by its State, Identity, and Behavior. Object’s state is defined by the information stored
in their instance fields. Object state is not fixed, but state changes depending on the message sent
to the object. Object’s identity is the unique identifier of the object from other objects. Behavior
of an object is what it can do at a given moment and what it can potentially do in the future.
They are created using New keyword. For instance, we can instantiate (create an object) class
Student above and create an object called mary as follows
Procedures
Procedures allow logical grouping of code into tasks. When a complex application is divided into
procedures, the code become more flexible and easier to maintain and debug. Procedures offers
the following advantages;
The code in a procedure is reusable – created and tested procedure can be called from
different places in the application
The application is easier to debug and maintain because source of errors in a procedure
are easier to trace than in entire application.
Types of procedures
There are two types of procedures;
Function procedure – perform a specific task and return a value to the calling
statement. Delimited by Function…End Function keywords.
Sub procedure – perform specific task but do not return a value to the calling
statement.
Namespaces
Namespaces are a way to group related classes together. They provide proper organization of
classes, so that they are convenient to use. Often if other people’s code are used, there arises
conflicts between method names. Such conflicts are avoided through namespaces. Namespaces
can contain classes, structures, enumerations, delegates, interfaces, and other namespaces.
NB: if own namespaces are created, it is advisable to prefix namespaces by application name to
ensure namespaces do not conflict with existing namespaces.
Exception handling
Errors and exceptions may occur during code development and often cause sudden failure of
programs. Structured exception handling in VB.NET provide a better and more robust way to
handle errors and exceptions. Exceptions are objects that are raised at runtime to abnormal
behavior in the application. Try..Catch..Finally keywords are used. (To be discussed and
implemented later).
Garbage collection
Objects usually have a lifetime, which is managed through garbage collection. When an objects
gets into scope, it occupies memory and must release that memory once it gets out of scope.
Released object references are automatically reclaimed by the operating system. Garbage
collection is therefore the process of reclaiming memory when the CLR decides that the object
references are no longer in use.
OOP concepts
VB.NET is a full-fledged player in the world of Object-oriented (OO) programming languages.
The primary advantage of OO languages compared to their procedural predecessors is that not
only can you encapsulate data (properties) into structures, but can also encapsulate behaviors as
well. For instance, a car is not only described by its color, number of tires etc. (properties), but
can also be described as an object that can speed up and slow down (behaviors/methods). In
addition, behavior can be propagated from one object to another, and this is where inheritance
comes in.
Inheritance
Inheritance is the ability to create new classes based on existing class. The new created class
acquires all the properties, methods, and events of the base class and can add its own properties
and methods. The common terms used when referring to classes in inheritance are derived and
base classes. The base class is the original class, or the framework class from which other
classes acquire properties while a derived class is a class that acquire properties and methods
from the base class. The Inherits keyword is used inside the derived class following the name of
class that it inherits from. For example, consider class Student that inherits properties and
methods of class Person and adds its own members.
Public Class Person
Return gender
End Function
End Class
Class Student
Inherits Person
no_of_units = 6
Return no_of_units
End Function
End Class
Class Student acquires (inherits) name and gender properties and showgender() method and adds
no_of_units property and Units() method as its members. Cumulatively, Student ends up with 3
fields and 2 methods.
NB: in .NET, all classes are inheritable by default unless they are defined with NotInheritable
keyword.
Encapsulation
Encapsulation is a term that is used to mean ‘data hiding’. Through encapsulation, actual
implementation of properties and methods in a class are concealed from the outside world. The
end goal is to provide a set of statements that must execute while hiding the behind-the-scenes
details. Code can therefore be modified without affecting or modifying the structure of the
program. NB: properties and methods that shall be used to access the hidden data must be
defined. For example, consider a class person with first_name and age as the class members.
Both members are private and can be set and retrieved using the properties FirstName and
Personage as shown below, but not directly. (To be discussed later in details in Class chapter).
Public Class Person
Get
Return first_name
End Get
Set(ByVal value)
first_name = value
End Set
End Property
Get
Return age
End Get
Set(ByVal value)
age = value
End Set
End Property
End Class
Polymorphism
Polymorphism means “more than one form”. It is the capability to have methods and properties
in multiple classes that have the same name and can be used interchangeably, even though each
class implements the same properties or methods in different ways. In VB.NET, this is known as
inheritance-based polymorphism. In implementing polymorphism, the following terminologies
are used.
Overridable: allows a property or method in a class to be overridden in a derived class.
Overrides: overrides an overridable property or method defined in the base class.
NotOverridable: prevents a property or method from being overridden in a derived
class.
MustOverride: Requires that a derived class override the property or method of a base
class.
Example of polymorphism: Notice method noofdoors() is defined in both classes with the same
name, and each class implements the method differently.
Class Sedan
door = 1
Return door
End Function
End Class
Inherits Sedan
door = 2
door = door + 4
Return door
End Function
End Class
Sub Main()
Console.ReadKey()
End Sub
For variables with dissimilar type specifiers can be declared as shown in example below;
Dim a As Integer, n As String, declares two variables, a of type integer and n as a
String. NB: initialization can be done on variables declared in the same line as in example
shown below provided the variables are of dissimilar data types; Dim a As Integer = 2,
n As String = "DIT 0303", declares a as integer and initializes it with value 2 and n as
string and initializes it with a string literal “DIT 0303”.
NB: Dim is applicable within a procedure block. Variable declaration variations exist depending
on where you use the variable and accessibility (scope). If declared inside a class, allowable
scope can be public, protected, friend, private, shared or static. The basic syntax in such cases is:
[Public|Protected|Friend|Private|Static|Shared] variable-name As type;
E.g. Private myInt as Integer
Public myInt as Integer etc.
By Daniel Wainaina @2016 9
VB.NET
Constants
A constant is a variable that holds a value that does not change throughout the execution of the
application. To declare a constant, Const keyword is used within a procedure or at declaration
sections of classes or modules. They can be declared with the scope of Private,Public, Friend,
Protected or Protected friend. The syntax is: [scope] Const constant-name [As type]
=expression.
For example, Private Const hourly_rate As Double = 120.50, defines a constant called
hourly_rate that stores value 120.50 throughout the application.
Comments
These are statements that are neither executed nor processed by VB.NET. They do not take up
room in your compiled code. Single quote is used as shown below.
Module CommentExample
Sub main()
Console.WriteLine("Hello World")
'this application prints a "Hello World" statement on the Console
Console.ReadLine()
End Sub
End Module
Concatenation operators – combine string variables with string expressions. For example;
Dim y As Double = 5
Dim x As Double = 4
Dim d As Double
d = y & x
MsgBox(d) ‘ Returns 54
Similarly,
Module Module1
Sub Main()
Dim y As String = "SCT121"
Dim x As String = "2015"
y = y & "-7491/" & x
MsgBox(y) 'Returns SCT121-7491/2015
End Sub
End Module
Assignment operator – is used to set value to a variable. Assignment operators can take
either of the forms shown below.
Assignment operators
Operator Action Description
= Equals assignment variable=expression
+= Addition/concatenation variable+=expression
assignment
-= Subtraction assignment variable-=expression
*= Multiplication assignment variable*=expression
/= and \ Division assignment floatingpointvariable/=expression,
= integralvariable\=expression
^= Exponentiation assignment variable^=expression
&= String concatenation variable&=expression
assignment
Comparison operator – evaluates an expression on the right-hand side of the equals sign
and return a Boolean True or False based on the comparison of the expressions. The syntax is
Result = expression1 comparison_operator expression2
They include; <, <=,>.>=, =, Is (object comparison), and Like (string pattern match).
Logical/bitwise operators – used for logical evaluation of Boolean expressions and bitwise
evaluation for numeric expressions. Syntax: result= expr1 operator expr2
They include And, Or, Not, Xor, AndAlso etc. for example
Dim x as integer=20, y as integer=15.
Result= Not(x>y) ‘Returns False.
Operator Precedence
//students to research
Operator example
Consider the following expressions, indicate the results
Dim x As Double = 54.63
Dim y As Double = 22.24
Dim a As String = "6"
Conversions
Programmers may want to convert data from one type to another, e.g., from Integer to Double.
VB.NET requires that explicit conversion (casting) be made whenever there is possibility of loss
of information (lossy conversion), e.g. when you convert a Double to an Integer, there is
possibility of losing information. This kind of conversion is referred to as narrowing conversion.
On the other hand, if there is no potential loss of information (lossless conversions), VB.NET
automatically (implicitly) makes the conversion. This is referred to as widening conversion.
VB.NET makes type conversion safe using Option Strict. When Option Strict is set On, it
disables implicit narrowing conversions. For example, the code segment below raises
compilation error.
Option Strict On
Module Module1
Sub Main()
Dim d As Double = 1.123
Dim s As Single
s = d
Console.WriteLine(s)
End Sub
End Module
In such cases, conversion (cast) functions are used. They make type conversion safe. They
include:
Conversion Functionality
Function
CBool Makes an expression a Boolean
CByte Makes an expression a byte
Cint Makes numeric expression an integer by rounding
CLng Makes a numeric expression long integer by rounding
CSng Makes a numeric expression single precision
Cdate Makes a date expression a date
CDbl Makes a numeric expression double precision
CDec Makes a numeric expression of the currency type
CStr Makes an expression a string
CChar Converts the first character in a string to a Char
Therefore, the error in the above code segment can be corrected through applying CSng function
to variable d as shown below;
s = CSng(d) ' safe conversion from Double to Single
Option statements
There are three Option statements which affect the behavior of the compiler. If used, they must
appear before any declarations in the same source file. They include:
Option Compare – controls the manner in which strings are compared to each other. The
syntax is Option Compare [Binary|Text]. If Binary is specified, strings are compared
based on their internal binary representations (case-sensitive comparisons). If Text is
specified, strings are compared based on case-insensitive alphabetical order. Default is
Binary.
Option Explicit – determines whether the compiler requires all variables to be explicitly
declared before use. The syntax is Option Explicit [On|Off]. If On the compiler requires
all variables to be declared before use and if Off considers variable’s use to be an implicit
declaration. The default is On.
Option Strict – controls the implicit type conversions that compiler will allow. The
syntax is Option Strict [On|Off]. If On the compiler only allows implicit widening
conversions and hence narrowing conversions must be explicit (cast functions must be
used). If Off compiler allows implicit narrowing conversions, and this would result in
runtime exceptions unforeseen by programmers. The default is Off. It is considered good
programming practice to require strict type checking.
3. CONTROL STRUCTURES
Programs are written to carry out a set of tasks, some of which require them to adjust their
behavior depending on the user input. VB.NET support such programs through statements which
execute a program conditionally, or repeating a set of statements. Such statements include
If..Then..Else and Select…Case, which execute programs conditionally (Selection Structures),
and Do…Loop, While…End While, and For..Next, which repeat statements conditionally
(Repetition Structures).
Selection Structures
IF...THEN Statement
In VB.NET there are many forms for the IF statement. They all work by evaluating some
expression and if the expression is correct (true) then the code within the IF block is executed. It
takes the form
If expression Then
Statement
Statement
….
End If
For example, consider a program that accepts two integers and determines whether they are
equal or which is greater than the other. Using IF statement, would be written as follows;
Sub Main()
Dim A As Integer
Dim B As Integer
A = InputBox("enter the value of A")
B = InputBox("enter the value of B")
If A > B Then
MsgBox(A & " is greater than " & B)
End If
If A < B Then
MsgBox(A & " is smaller than " & B)
End If
If A = B Then
j MsgBox(A & " is equal to " & B)
End If
End Sub
IF…THEN...ELSE Statement
This is another variation of the IF statement which takes the following form;
If expression Then
Statement
Statement
…
Else
Statement
Statement
…
End If
The expression is evaluated where, if True, the statement following Then is executed and if false,
the statement following Else is executed. For instance, consider a program that sets discount for
customers based on quantity ordered. It would be written as follows;
Sub Main()
Dim QntOrdered, Discount As Integer
Console.WriteLine("Enter Quantity Ordered")
QntOrdered = Console.ReadLine()
If QntOrdered > 10 Then
Discount = 20
Else
Discount = 10
End If
Console.WriteLine("Discount= " & Discount)
Console.ReadLine()
End Sub
IF…ELSEIF…THEN Statement
This is an extension of IF…ELSE statement that takes multiple If statements combined into one.
Its form is as follows:
If expression1 Then
Statement
Statement
…
ElseIf
expression2 Then
Statement
Statement
…
ElseIf expression3 Then
Statement
Statement
…
Else
Statement
Statement
…
End If
For example, consider a program that accepts age and determines if a person is a child, teenager,
young man or old man as shown below,
Sub Main()
Dim MyAge As Integer
MyAge = CInt(InputBox("Enter your Age"))
If MyAge < 13 Then
' you must be a child
MsgBox("Hello Child")
ElseIf MyAge < 20 Then
' you are a teenager
MsgBox("Hello Teenager")
ElseIf MyAge < 35 Then
' Your age is acceptable
MsgBox("Hi there young man")
Else
' the person is old
MsgBox("Hello there old man")
End If
End Sub
In this case, if expression 1 is evaluated to true, then its statements are executed and the rest of
the IF statements are ignored. If not, the expression 2 is evaluated and its corresponding
statements are executed while other checks are ignored…until Else if all expressions evaluate
false.
Exercises
1. Write a program that outputs the grade scored by a student once the marks are supplied.
(use Diploma in IT system)
2. Write a program that accepts a digit and outputs the corresponding day of the week. E.g.
1= Monday, 2=Tuesday…etc.
Expressionlist refers to the constants or expressions that are compared with the result of
expression mentioned with the Select..Case statement. The End select statement marks the end of
the Select..case.For example, consider a program that outputs the name of months once
corresponding number is given.
Dim month As Integer
month = InputBox("enter number")
Select Case month
Case 1
MsgBox("This is January")
Case 2
MsgBox("This is February")
Case 3
MsgBox("This is March")
Case 4
MsgBox("This is April")
Case 5
MsgBox("This is April heading to may")
Case Else
MsgBox("Am tired I will define the rest later")
End Select
In some applications, it is practically impossible to write case statements for each and every
value in a range, based on a condition given. In such situations, conditional expressions are
specified instead of values. Is keyword is used to specify this conditional expression.
For example, consider a program that gives discounts depending on quantity bought as shown
below. Since a range of values is required, Is keyword is used followed by conditional
expression.
Dim Quantity, Discount As Integer
Quantity = InputBox("enter quantity bought")
Select Case Quantity
Case Is <= 10
Discount = 10
Case Is <= 20
Discount = 20
Case Is <= 30
Discount = 30
Case Is > 30
Discount = 40
Case Else
MsgBox("Invalid Entry")
End Select
MsgBox(Discount)
Alternatively, ranges in each Case statements given can be specified using To keyword.
For example;
Select Case Quantity
Case 1 To 10
Discount = 10
Case 11 To 20
Discount = 20
Case 21 To 30
Discount = 30
Case Is > 30
Discount = 40
Case Else
MsgBox("Invalid Entry")
End Select
MsgBox(Discount)
You may also want to have the same set statements for more than one value of the expression. In
such cases, multiple values or ranges in a single Case statement is specified. For example;
Dim number As Integer
number = InputBox("enter number")
Select Case number
Case 11, 13, 17, 19 ‘Notice several values are specified
MsgBox("This is Prime Number")
Case 12, 14, 16, 18, 20
MsgBox("even Number")
Case Else
MsgBox("Invalid Entry")
End Select
Repetition Structures
Do…Loop statements
They are used to execute a set of statements repeatedly. The syntax is:
For example, consider a program that prints integers in the range 1 to 10. It can be written in
either of the following forms;
2 a) Dim i As Integer = 1
Do Until (i > 10)
Console.WriteLine(i)
i += 1
Loop
Console.ReadLine()
b) Dim i As Integer = 1
Do
Console.WriteLine(i)
i += 1
Loop Until (i > 10)
Console.ReadLine()
While…End While
This repeats a statement(s) as long as a condition is true. The syntax is;
While condition
Statement(s)
End While
For example, the code below outputs integers in the range 1 to 10 using While…End While
loop.
Dim i As Integer = 1
While i <= 10
Console.WriteLine(i)
i += 1
End While
Console.ReadLine()
For…Next Statement
This loop statement repeats statement(s) for a specified number of times. The syntax is;
For Counter=<startvalue> To <endvalue> [step Value]
Statement(s)
Next [counter]
NB: counter is a numeric value. Startvalue is the initial value of the counter while endvalue is
the final value of the counter. Stepvalue is the value by which the counter is incremented or
decremented. It’s optional and can either be positive or negative. If omitted, default is set to
1. To exit the For loop, Exit For is used and causes statements after Next statement to be
executed.
For example, the program below uses For…Next to print integers in the range 1 to 10.
Dim i As Integer = 1
For i = 1 To 10 Step 1
Console.WriteLine(i)
Next i
Console.ReadLine()
To print only the first seven integers, for instance, Exit..For can be used as follows;
Dim i As Integer = 1
For i = 1 To 10 Step 1
Console.WriteLine(i)
If i = 7 Then
Exit For
End If
Next i
Console.ReadLine()
Exercise
1) A survey has to be carried to discover the most popular sport. Every participant is
required to type a letter representing the sport they support as follows; A-Athletics, S-
Swimming, F-Soccer, and B-badminton. Letter Q is used to finish the tally. Write an
application that outputs the results and shows the popular sport.
Solution
Sub Main()
Dim F, B, S, A As Integer
Dim vote As String
Do
vote = InputBox(" Select the Sport you Support:A-Athletics, S-
Swimming, F-Soccer, and B-badminton.Enter Q to finish the tally").ToUpper
Console.ReadLine()
End Sub
2) Write an application to compute the sum of all numbers divisible by 9 between 50 and
200.
3) Write an application that compute the sum of all even numbers and product of all odd
numbers between 1 and 100.
4. ARRAYS
At times, one may need to store multiple instances of similar data. One way is to declare
separate variables, which you have to remember their names. Alternatively, one can store
such values in an array. Array allow programmers to store multiple values of similar data
type without necessarily creating separate variables. Array store all the items in a single
variable, and each item can be referenced using array index or subscript. Values stored in an
array are called elements of an array.
Arrays have a lower bound and an upper bound. In VB.NET, the lower bound for an array is
always 0. So, if an array had 10 elements, the lower bound would be 0 and the upper bound
would be 9. Arrays can be single dimensional or multidimensional. Dimensions of an array is
determined by the number of subscripts that are used to identify the position of an array
element. For example, an element in a single-dimensional array is identified by only a single
subscript and two subscripts in a two dimensional array.
Single dimensional array
This is an array that have elements identified by a single subscript. It can be thought as a row
of items that contain values.
Declaring an array
The syntax for declaring an array is similar to that of other variables except that parentheses
are added after the variable name to indicate that it is an array. Dim or Scope (Public, Private,
Friend etc.) keyword are used. The syntax is:
Dim array_name (num_of_elements) [as element type).
NB: array_name refers to the name of the array, num_of_elements refers to the number of
elements the array can contain (size) and element type refers to the data type of elements.
For instance, the statement below declares an array of integers with 10 elements.
Dim array1 (10) As Integer or Dim array1() As Integer= New Integer (10){}
You can also initialize the values of an array during declaration as shown below.
Dim array1 () As Integer= {0, 1, 2, 3, 4}
Notice that the parentheses are left blank because in such cases, the array is automatically
dimensioned to the correct number of elements.
To read or write an element in the array, array name followed by the parenthesis, inside
which is the number that indicates which element in the array is being referenced, is used. For
example;
array1(0) =5 ‘assigns value 5 to the first element of the array (write operation).
b = array1(3) ‘ reads the value of the fourth element of the array and assigns it to variable b
(read operation).
For example, the program below sets each element to the index value of the array, and
outputs those values.
Sub Main()
Dim i As Integer
Dim arr(5) As Integer
For i = 1 To 4
arr(i) = i ' sets each element of array to its index value.
Next
'lets now output array elements
For i = 1 To 4
Console.Write(" " & arr(i))
Next
Console.WriteLine()
'output 4th element
Console.Write("The Fourth element of array is: " & arr(3))
Console.ReadLine()
End Sub
Exercise
1) Write an application that captures marks for 10 students and computes their average.
Sub Main()
Dim arr(9), i As Integer
Dim sum As Integer = 0
Dim avg As Double
For i = 0 To 9
arr(i) = InputBox("Enter the mark")
sum += arr(i)
Next
avg = sum / 10
Console.WriteLine("Array elements")
For i = 0 To 9
Console.Write(" " & arr(i))
Next
Console.WriteLine()
Console.WriteLine("Sum is: " & sum)
Console.WriteLine("Average is: " & avg)
Console.ReadLine()
End Sub
2) Write an application that captures some values and determines the largest and smallest
among them.
3) Write an application that has an array containing student marks as follows; 55, 76, 90,
100, 34, 23, 84, 95, 100, 99. Given that pass mark is >=50, determine the number of
passed and failed students.
Sub Main()
Dim marks() As Integer = {55, 76, 90, 100, 34, 23, 84, 95, 100,
99}
Dim pass, fail As Integer
Dim i As Integer
For i = 0 To 9
If marks(i) >= 50 Then
pass = pass + 1
Else
fail = fail + 1
End If
Next
Console.WriteLine()
Console.WriteLine("Passed: " & pass)
Console.WriteLine("Failed: " & fail)
Console.ReadLine()
End Sub
Multidimensional Arrays
Multidimensional arrays are used to store related data together. For instance, one may want to
store employee codes along with their salaries. In such situations, two or three dimensional
arrays are used. An array can have several dimensions although it is uncommon to go above
three dimensions. This means, an array can have one row to multiple rows of columns.
For example, an array with three rows and five columns can be represented as follows.
Row 1, column1 ..
Row 3, column
5
To declare such an array, the following syntax is used;
Dim arr (2, 4) As String ‘NB: indices start from 0
This declares a two dimensional array called arr with 3 rows and 5 columns that stores string
type data.
To declare a multidimensional array, one has to separate the length for each row by a comma.
For example, a 2 dimensional array with 5 elements in the first dimension and 10 elements in
the second dimensions would be declared as follows;
Dim arr (5, 10) As [Data type]
//Declare a 3 dimensional array called Facts that stores 10 integer elements in all of its
dimensions.
Dim Facts (10, 10, 10) As Integer
//Declare a 2 dimensional array that stores the code and names of 10 employees
Dim emp_details (10, 2) As String
Multidimensional arrays can also be initialized during declaration. In this case, the
parentheses is left empty except for a comma for each additional array dimension. For
example, the following declaration statement declares a 2 dimensional array and initializes it
with integer values as shown.
Dim arr (,) As Integer = {{11, 12, 13}, {21, 22, 23}}.
To output the elements stored in this array, the following section of code would be used
Sub Main()
Dim arr(,) As Integer = {{11, 12, 13}, {21, 22, 23}}
Dim i As Integer
Dim j As Integer
For i = 0 To 1
For j = 0 To 2
Console.Write(arr(i, j) & " ")
Next
Console.WriteLine()
Next
Console.ReadLine()
End Sub
For i = 0 To 1
For j = 0 To 2
Console.WriteLine("Enter Element in row:" & (i + 1) & "Column:"
& (j + 1))
arr(i, j) = Console.ReadLine()
Next j
Next i
Console.WriteLine("********OUTPUT********")
For i = 0 To 1
For j = 0 To 2
Console.Write(arr(i, j) & " ")
Next j
Console.WriteLine()
Next i
Console.ReadLine()
NB: VB.NET provides LBound and UBound functions used to determine the upper and
lower bounds of an array. The LBound function is used to retrieve the lower bound of the
array (always zero), and the UBound function returns the upper bound of the array. In single
dimensional array, one doesn’t have to tell the function which dimension to return the value
for. By default, it returns the value for the first row and therefore, no need to pass in a value
for single dimension array. For instance, the code segment below, array elements are assigned
the value of array index. Notice that the dimension whose value is returned was not indicated.
For i = LBound(arr) To UBound(arr)
arr(i) = i
Next
However, with multidimensional array, one need to tell the function which dimension to
return the value for, and therefore, value for dimension must be passed. For instance, in the
code segment below, notice that in both LBound and UBound functions, the value for the
dimension they are returning value for is indicated.
Dim arr(,) As Integer = {{11, 12, 13}, {21, 22, 23}}
Dim i, j As Integer
For i = LBound(arr, 1) To UBound(arr, 1) ‘returns value for dimension
1
For j = LBound(arr, 2) To UBound(arr, 2) ‘returns value for
dimension 2
Console.Write(arr(i, j))
Next
Console.WriteLine()
Next
Console.ReadLine()
Dynamic arrays
There are some situations in which you may not know the number of elements to be stored in
an array or you may need to change the size of the array. In such situations, dynamic arrays
are used. Dynamic arrays are arrays whose sizes can vary or change during the execution of a
program. To accomplish this, ReDim keyword is used. During declaration, the size of the
array is not specified but it is set later when ReDim keyword is used.
NB:
1) ReDim statement specify or change the size of one or more dimensions of an array
that has already been declared. However, it doesn’t change the number of dimensions
in an array.
2) When ReDim statement is executed, the existing contents of the array are lost. This is
because the ReDim statement releases the array resources and creates a new array.
3) ReDim statement can be used at the procedure level only and not at the class or
module level.
For example, the code segment below doesn’t specify the size of the array during declaration,
but it is later specified using ReDim during runtime.
Dim arr( ) As Integer
Dim i As Integer
ReDim arr(i)
For i = 0 To 3
arr (i) = 0
Next
In this example, array is first initialized with three elements and output given. The size of
array is later increased to hold three more elements using ReDim statement and output later
given.
ReDim key word creates a new array and existing data is lost. However, one may want to
retain the data stored in the array even after resizing the array. In such situations Preserve
keyword is used. For example, even after resizing the array in the example above, we may
want to retain the initialized elements. Therefore, the Preserve keyword is used as shown
below;
Sub Main()
Dim arr() As Integer = {12, 13, 14}
Dim i As Integer
Console.WriteLine("Output before redefinition")
For i = LBound(arr) To UBound(arr)
Console.Write(arr(i) & " ")
Next
Console.WriteLine()
This is because the values of the first three elements are retained and the added elements
weren’t assigned values. Suppose we assign the newly added elements with values 15, 16 and
17 respectively.
Dim arr() As Integer = {12, 13, 14}
Dim i As Integer
Console.WriteLine("Output before redefinition")
For i = LBound(arr) To UBound(arr)
Console.Write(arr(i) & " ")
Next
Console.WriteLine()
ReDim Preserve arr(5)
arr(3) = 15
arr(4) = 16
arr(5) = 17
Console.WriteLine("Output after redefinition")
For i = LBound(arr) To UBound(arr)
Console.Write(arr(i) & " ")
Next
Exercises
1) Write a VB.NET application program that initializes the elements of ten-element
array to the integers 2, 4, 6…20 and displays the indices and array elements contents
in a tabular format.
2) Write a program that prints a ten by ten multiplication table (5 marks).
Solution
Sub Main()
Dim table(9, 9), i, j As Integer
For i = LBound(table, 1) To UBound(table, 1)
For j = LBound(table, 2) To UBound(table, 2)
table(i, j) = (i + 1) * (j + 1)
Next j
Next i
For i = LBound(table, 1) To UBound(table, 1)
For j = LBound(table, 2) To UBound(table, 2)
Console.Write(table(i, j) & " ")
Next j
Console.WriteLine()
Next i
Console.ReadLine()
End Sub
NB: It accepts no arguments and thus the parentheses that hold the argument list is empty.
Calling a Sub Procedure
After creating a sub procedure, it is invoked explicitly by a calling statement. The syntax
used for this purpose is;
[Call] <procedure-name> ([argument list]). The Call keyword is used to execute code inside
of a sub-procedure. It is however, optional. For example, to invoke compute-area sub
procedure above, one of the following statements are used.
Call compute_area()
or
compute_area()
With each call to a procedure, results may differ depending on the data passed as arguments.
Procedure arguments can be variables, constants or expressions. Arguments, while creating
procedures, are declared the same way as variables. The default data type of procedure
argument is Object. However, different data types can be specified using the As clause.
The syntax for declaring procedure arguments is: variable-name As data type.
Arguments can be passed to a procedure in two ways, namely;
By value – when an argument is passed by value, a copy of the argument is passed
when the procedure is called. Therefore, the value of the original variable remains
unchanged even if the procedure modifies the value that is passed.
By reference – when an argument is passed by reference, a reference to the original
variable is passed. Therefore, the value of the original variable is affected
immediately if the procedure modifies the value that is passed.
Suppose the compute-area sub procedure above is modified to accept radius and PI as
arguments. It would then change to the following format;
Public Sub compute_area(ByRef radius As Double, ByVal PI As Double)
Dim area As Double
area = PI * (radius ^ 2)
MsgBox("The area of a Circle of radius: " & radius & " is: " & area)
End Sub
Notice that the calling statement must then pass values or references to arguments as shown
below.
compute_area(7, 3.142) ‘ 7 is passed as value for variable radius while
3.142 for variable PI.
Function procedures
Like Sub procedures, Function procedures (or generally functions), are created inside a class
or a module. However, unlike sub procedures, Function procedures return value. Because
they return a value, one need to define the data type for the return value while creating a
Function procedure. The syntax for creating a Function procedure is:
[access modifier] Function procedure-name ([argument-list]) As type
Statements
End Function
NB: Function keyword indicates that the procedure is a function, As type represents the data
type of the return value of the function, and End Function indicates the end of the function
procedure.
For example, consider the Function below that prompts the user to enter the radius of the
circle, computes and returns the area to the main procedure, which then displays the returned
area.
Public Function compute_area() As Double
Dim radius, area As Double
Const PI As Double = 3.142
radius = CDbl(InputBox("Enter the radius"))
area = PI * (radius ^ 2)
Return area
End Sub
Notice the Return keyword is used to return a value from the procedure.
Functions can also accept arguments. For example, the function below accepts radius and PI
as arguments, then computes and returns area to the calling statement.
Public Function compute_area(ByRef radius As Double, PI As Double) As Double
Dim area As Double
area = PI * (radius ^ 2)
Return area
End Function
Calling a Function
To call a function, a variable can be created to accept the returned value from the function as
demonstrated below;
Dim circle_area As Double ‘creates a variable
circle_area = compute_area(7, 3.142) ‘created variable accepts the
returned value
MsgBox("The Area =" & circle_area)
Or
Call a function within an expression as demonstrated below;
MsgBox("the area is: " & compute_area(7, 3.142)) ‘Notice function name in bold
Example
Write a VB.NET application that captures the length and width of a rectangle using a
procedure, computes area and perimeter using functions that return computed values
respectively, and displays the values using another procedure.
Module Module1
Private length, width As Double
'a function that accepts two parameters, computes and returns area
Private Function compute_area(ByRef len As Double, ByRef wid As Double) As
Double
Dim area as double
area = len * wid
Return area
End Function
'A function that accepts two parameters, compute and return perimeter
Private Function compute_perimeter(ByRef len As Double, ByRef wid As
Double) As Double
Dim perimeter as double
'a sub procedure that calls the above functions and displays value
returned
Sub displaydetails()
Console.WriteLine("the area is:" & compute_area(length, width))
Console.WriteLine("the perimeter is:" & compute_perimeter(length,
width))
End Sub
End Module
NB: the main procedure calls only getdetails and displaydetails only. displaydetails is the
procedure within which compute_area and compute_perimeter functions are called.
CLASSES
A class is one form of data type intended to represent the definition of real-world objects. A
class declaration defines the set of members – fields, properties, methods, and events – that
each object of the class possesses. Together, these members define object’s state and
functionalities. An object is simple instance of a class. Creating an object of a particular class
is called instantiating an object of the class.
Class is created using Class…End Class block. It is inside these keywords that members are
defined. For example, if you want to create a class that represents a Customer, you would
define it as follows;
Public Class Customer
'members go in here
End Class
An application can contain more than one classes. Even though you can have multiple classes
in a single file, it is advisable to have a single class per file. This is because it makes it easy to
navigate from file to file to find code. Classes are visible from inside the same project if
scope qualifier is not specified. However, keywords such as Public, Friend, Protected, Private
etc. can be used to explicitly define visibility of classes to other applications.
It is required that class names should be name or names combination but not prefix or
underscore. If the class name include multiple words, Pascal case should be used, e.g.
(CustomerDetails).
Class fields are variables declared directly inside the class block. For example, Class Person
can have fields such as names, dateofbirth, and address among others. Such class can be
defined as shown below.
Class methods are procedures that contain application logic. They can be sub or function
procedures. For example, the class Circle below have two functions and one sub procedures
as shown below;
Class Circle
'class fields
Const PI As Double = 3.142
Private circlearea As Double
Private circleperimeter As Double
Private radius As Integer
'methods and implementations
Public Function calcarea(ByRef rad As Integer) As Double
Dim area As Double
area = PI * rad * rad
Return area
End Function
Public Function calcperimeter(ByRef rad As Integer) As Double
Dim perimeter As Double
perimeter = PI * rad * 2
Return perimeter
End Function
Public Sub Print()
radius = InputBox("Enter radius of circle")
circlearea = calcarea(radius)
circleperimeter = calcperimeter(radius)
MsgBox("The area is: " & circlearea & "The perimeter is:" &
circleperimeter)
End Sub
End Class
Class properties are used to store variables in a class. They exist to provide an object
oriented way of setting and getting variables. They allow encapsulation of each instance of
class created. Properties are created using Property…End Property block. For example,
Public Class Person
Get
Return first_name
End Get
Set(ByVal value)
first_name = value
End Set
End Property
Get
Return age
End Get
Set(ByVal value)
age = value
End Set
End Property
End Class
Properties control what happens to the property when accessed or set. Properties should be
used in place of fields if;
Variables are read-only
Validation beyond data type validation is needed
Variables change the state of the object
Other variables within the class need to change if these variables changes.
Class events are notifications that cause something to happen or occur in response to
something happening. In classes, events can be raised and handled (consumed). They are
raised with RaiseEvent statement and handled with either AddHandler or Handles statements.
For example, below is an example of click event raised by a button and handled once the
button is clicked. Event click is handled as follows; values of base and height are read from
respect textboxes, hypotenuse computed and displayed on textbox, and a label text is set to
“computing hypotenuse”.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click
Dim b, h, hyp, hpp As Double
b = CInt(TextBox1.Text)
h = CInt(TextBox2.Text)
hpp = Math.Pow(b, 2) + Math.Pow(h, 2)
hyp = Math.Sqrt(hpp)
TextBox3.Text = hyp
Label1.Text = "Computing Hypotenuse"
End Sub
End Class
OBJECTS
An object is an abstraction of a real-world entity or relationship. Class is a blueprint of a real
world concept that provides the basis from which instances of specific objects are created.
For example, to create a Customer object, there must be a Customer class that contains all the
code (methods, fields, events, properties, etc.) necessary to create Customer objects. Based on
such a class, any number of objects of that class can be created. All the created objects from a
particular class are identical in terms of what they can do and the code they contain, but each
of the created objects contain its own unique data. This means that each object will represent
a different physical entity. For example, each object of Customer class will represent a
different physical customer.
Object declaration and instantiation
Objects are created using New keyword, which indicates that a new instance of a particular
class is needed. A number of variations exist on how and where New keyword can be used.
i) The first and obvious way is to declare an object variable and then create an instance
of the object.
The syntax is:
Dim Object_name As Class
Object_name=New Class()
For example, one can create an object called cust1 of class Customer as follows;
Dim cust1 As Customer 'declaring a variable of type Customer
(class)
cust1 = New Customer() 'creating an instance of the object
ii) The second way is combining the declaration of the variable with creation of instance.
The syntax is: Dim Object_name As New Class()
For example, the above example (i) can be shortened as;
Dim cust1 As New Customer()
iii) The third way is to both declare the object variable and immediately create an
instance of the class that one can use. This way provides a great deal of flexibility
while remaining compact. The syntax is : Dim Object_name As Class= New Class()
For example, the above example (i) can be written as;
Dim cust1 As Customer = New Customer()
Once an instance of a class is created, it can be used to access the functionality using the dot
operator(.). Depending on the specified scope, class members can be accessed using the
created object. For instance, to access a field or method, you use Object_name.field or
Object_name.method_name.
For example, consider the following Class Customer
Public Class Customer
Private Firstname As String
Private Lastname As String
Private address As String
Private Phonenumber As String
Sub getdetails()
Console.WriteLine("Enter Customer's First Name")
Firstname = Console.ReadLine()
Console.WriteLine("Enter Customer's Last Name")
Lastname = Console.ReadLine()
Console.WriteLine("Enter Customer's Address")
address = Console.ReadLine()
Console.WriteLine("Enter Customer's Phone Number")
Phonenumber = Console.ReadLine()
End Sub
Sub print()
Console.WriteLine("*****CUSTOMER DETAILS*****")
Console.WriteLine("First Name:" & Firstname)
To access its functionalities (getting details and printing details) an object cust1 is created and
used as shown below. Notice the use of the dot(.) operator.
Dim cust1 As Customer = New Customer()
cust1.getdetails()
cust1.print()
Exercise
1) Write a VB.NET console application that uses a Class called Circle. The class should
have three (3) procedures, one that computes and returns area, another which
computes and returns perimeter, and a final one that accepts radius from user and
prints the area and perimeter returned by the two prior procedures. NB: the main
procedure should only create an object of class Circle and use the object to call the
procedure that prints the values.
Constructors
Constructors can be quite useful because they allow one to instantiate an object with some
values already in it. In VB.NET, a constructor is a sub procedure called Sub New (). With
constructors code can be written to establish database connection or read values form
database. For instance, suppose every time an object of class Customer above is created, a
message “CREATING OBJECT” is displayed. A constructor would be used as follows;
Public Sub New()
Console.WriteLine("CREATING OBJECT")
End Sub
Inheritance
Inheritance is a very powerful form of code reuse in which, one class that contains some
properties and methods become the basis for other classes. This class is called a base class.
Classes that then use this base class are known as derived classes. Most often, the derived
classes extend the functionality of the base class.
For example
We can define a simple Person base class with Fname and Sname fields as follows.
Public Class Person
'fields visible outside class
Public Fname As String
Public Sname As String
End Class
To inherit from this class, inherits keyword is used. For example, suppose a Class Employee
inherits from Person. All you need is an inherit clause immediately after the Class statement
as shown below.
'class Employee inherits from Person
Public Class Employee
Inherits Person
'
'
End Class
The derived class inherits all Public and friend fields, properties, methods, and events of a
base class.
Extending the derived class
Derived class can be extended with new fields, properties, and methods by simply adding
these new members anywhere in the class block. For example, we can extend the derived
class Employee with new fields as shown below.
Public Class Employee
Inherits Person
'two new Public fields
Public basicsalary As Double
Public hoursworked As Integer
End Class
NB:
The MustInherit modifier can be used in class declaration to indicate that this class
cannot be instantiated- it can only be used as a base class in a derivation (also known
as abstract classes in OOP).
Public MustInherit Class Vehicle
It is possible to define a class from which it is not possible to inherit. This is done
with the NotInheritable keyword in class declaration. Eg,
Public NotInheritable Class Student
'
'
End Class
End Class
Public Class Student
Inherits Person
Public regno As String
Public Overrides Function print() As String
Dim completename As String
completename = Fname & " " & Sname & " " & regno
Return completename
End Function
End Class
End Class