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

VB.NET

.NET Framework is a Microsoft platform for developing component-based software, providing essential services for application development and deployment. It includes layers such as the Common Language Runtime (CLR), Base Class Library (BCL), and ASP.NET for user interface generation, while supporting object-oriented programming concepts like inheritance, encapsulation, and polymorphism. VB.NET, as part of the .NET ecosystem, utilizes assemblies, modules, classes, and procedures to organize code and manage data types, enabling developers to create robust applications.

Uploaded by

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

VB.NET

.NET Framework is a Microsoft platform for developing component-based software, providing essential services for application development and deployment. It includes layers such as the Common Language Runtime (CLR), Base Class Library (BCL), and ASP.NET for user interface generation, while supporting object-oriented programming concepts like inheritance, encapsulation, and polymorphism. VB.NET, as part of the .NET ecosystem, utilizes assemblies, modules, classes, and procedures to organize code and manage data types, enabling developers to create robust applications.

Uploaded by

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

VB.

NET

1. NINTRODUCTION TO .NET PROGRAMMING


1.1 Introduction to .NET Framework
.NET framework is a Microsoft’s platform for developing component-based software. It provides
fundamental advances in runtime services for application software. The framework provides
services necessary to develop and deploy applications for the loosely coupled, disconnected
internet environment. That is, it supports development of applications that can be free of
dependencies on hardware, operating system, and language compiler. It contains compilers and
other command-line utilities to link modules together and install .NET components.
.NET architecture
.NET Framework contains a number of components arranged in layers as shown in the figure
below

IDE Level

.NET Framework

Operating system Level

 Windows API and COM+ services


.NET offers an object oriented view of the operating system’s functions. Windows API helps in
making most calls into the .NET Framework. It ultimately resolves these calls into one of the
Windows kernel DLLs. .NET Framework rely on Component services, and therefore, .NET
components can take advantage of COM+ services such as transaction, synchronization and
security provided by COM+.
 Common Language Runtime
CLR is the first layer that belongs to the .NET Framework. This layer is responsible for .NET
base services such as memory management, garbage collection, structured exception handling,
and multithreading. That is, it manages code execution (loads and runs programs, and manages
their interactions) as well as services that .NET provides. The CLR “knows” what to do through
special data called metadata, contained within the applications. This metadata store a map of
where to find classes, when to load classes, and when to set up runtime context boundaries,
generate native code, enforce security, determine which classes use which methods, and load
classes when needed. It also determines when an object is used and when it is released. This is

By Daniel Wainaina @2016 1


VB.NET

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

By Daniel Wainaina @2016 2


VB.NET

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)

Private admno As String

Private firstname As String

Private YearofBirth As Integer

'member function

Public Function calculate_age(ByVal current_year As Integer, ByVal


YearofBirth As Long) as integer

Dim age As Integer

age = current_year - YearofBirth

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.

By Daniel Wainaina @2016 3


VB.NET

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

Dim mary As Student = New Student()

 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

By Daniel Wainaina @2016 4


VB.NET

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

Protected name As String

Protected gender As Char

Public Function showgender() As Char

gender = InputBox("Enter Gender")

Return gender

End Function

End Class

Class Student

Inherits Person

Dim no_of_units As Integer

Public Function Units() As Integer

no_of_units = 6

Return no_of_units

End Function

End Class

By Daniel Wainaina @2016 5


VB.NET

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

Private first_name As String

Private age As Integer

Public Property FirstName()

Get

Return first_name

End Get

Set(ByVal value)

first_name = value

End Set

End Property

Public Property Personage()

Get

Return age

End Get

Set(ByVal value)

age = value

End Set

End Property

End Class

 Polymorphism

By Daniel Wainaina @2016 6


VB.NET

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

Public door As Integer

Public Overridable Function noofdoors() As Integer

door = 1

Return door

End Function

End Class

Public Class Coupe

Inherits Sedan

Overrides Function noofdoors() As Integer

door = 2

door = door + 4

Return door

End Function

End Class

Sub Main()

Dim s As Sedan = New Sedan()

Dim c As Coupe = New Coupe()

Console.WriteLine("The no of doors for coupe is:" & c.noofdoors())

Console.WriteLine("And that of Sedan is:" & s.noofdoors())

Console.ReadKey()

End Sub

By Daniel Wainaina @2016 7


VB.NET

2. PROGRAMMING FUNDAMENTALS IN VB.NET


The main aim of this chapter is to discuss the syntax of VB.NET language that include basic
concepts such as identifiers, variables, operators, statements, etc.
 Identifiers
These are names given to namespaces, types (structures, classes, modules, delegates), type
members (methods, events, constructors, constants, fields, properties), and variables. Identifiers
must begin with either an alphabetic or underscore character, may be of any length, and after the
first character it may contain alphanumeric and underscore characters. NB: although VB.NET is
not case sensitive, the case of identifiers is preserved when applications are compiled. In
addition, identifiers may not match VB.NET keywords. Keywords are words with special
meaning in a programming language. They are reserved i.e., cannot be used for such purposes as
naming variables and subroutines. However, if it is very necessary to declare or use an identifier
that matches a keyword, the identifier must be enclosed in square brackets ([]). For example,
Public Class [Public] defines a class called Public. NB: Public is a keyword. (Students to search
for keywords in VB.NET)
 Data types
Types in VB.NET are divided into two categories: primitive (fundamental) and custom type.
Fundamental types are built-in types, each of which is an alias for a type supplied by the .NET
architecture. They include:
 Boolean - type limited to two values: True and False. Usually, logical operators result in
a Boolean type.
 Byte – holds a range of integers from 0 to 255 and represents values that can be held in
eight bits of data.
 Char – this holds any Unicode character (single character).
 Date – hold values that specify dates and times. Used for accessing, comparing and
manipulating dates and times.
 Decimal – holds decimal numbers with a precision of 28 significant decimal digits. Its
purpose is to represent and manipulate decimal numbers without the rounding errors of
the Single and Double types.
 Double – holds floating point numbers, which are 64 bit value.
 Integer - holds integers in the range -2147483648 through 2147483647.
 Long – is a 64bit integer data type that holds integers in the range -9223372036854775808
through
9223372036854775807.
 Object – this is the base type from which all other types are derived.
 Short – holds integers in the range -32768 through 32767.

By Daniel Wainaina @2016 8


VB.NET

 Single – holds a 32bit value.


 String – holds a sequence of Unicode characters
NB: of the fundamental types, all are value types (data itself is stored in the variable) except
object and string types which are reference types (reference to the data (pointer) is stored in the
variable and the data itself is stored somewhere else).
Custom types provide syntax for extending the type system. They include Structure, Enum,
Class, Interface, and Delegate and all .NET framework types that don’t derive from
System.ValueType.
 Variables
For a computer to process information or data, that data should be placed in computer’s memory
for different operations to be performed. Similarly, VB.NET application process data in memory
and therefore, memory must be allocated by defining variables. A variable is a named memory
location that allow programs to process data within it.
To define a Variable in VB.NET, Dim keyword is used, followed by variable name and finally
the As data type. Dim tells the computer that a variable will be defined while data type defines
the data to be stored and operations to be performed in that variable. For example,
Dim MyInt As Integer, defines a variable called MyInt which stores and performs
integer operations.
You can combine multiple declarations on a single line for variables of similar or dissimilar data
types. For variables of similar data types, variable names are separated by commas as shown in
example below
Dim i, j, k As Integer, makes i, j and k all integer variables. NB: you cannot
initialize when variables of similar data types are declared on the same line. i.e. Dim i,
j, k As Integer = 5 is not allowed.

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

 Operators and expressions


VB.NET offers numerous operators that fall into the arithmetic, assignment, comparison,
concatenation, logical and bitwise categories.
 Arithmetic operators supply basic algebraic functions as shown below.
Arithmetic Operators
Operator Action Description
+ Addition y=5+4 //9
- Subtraction y=5-4 //1
* Multiplication y=5*4 //20
/ (Regular division) and \(Integer Division y= 5/4 //1.25, y=5\4 // 1
division)
Mod Modulus y=5 Mod 4 // 1 ‘gives remainder
^ Exponentiation y=5^4 // 625

 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

By Daniel Wainaina @2016 10


VB.NET

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

For example, what is the output of the following code segment?


Dim x As Integer = 2
x ^= 2 + 3
MsgBox(x) //should return 32

 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"

By Daniel Wainaina @2016 11


VB.NET

Dim b As String = "5"


Dim z As Short
z = CShort(a) + CShort(b) 'Returns 11
MsgBox(a + b) 'Returns 65
z = x + y 'Returns 77, cannot take decimals hence narrowing takes place
a = x + y 'Returns 76.87
a = x.ToString + y.ToString 'Returns 54.6322.24 since after conversion to
string, concatenation occurs

 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

By Daniel Wainaina @2016 12


VB.NET

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.

By Daniel Wainaina @2016 13


VB.NET

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

By Daniel Wainaina @2016 14


VB.NET

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

By Daniel Wainaina @2016 15


VB.NET


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.

 The SELECT…CASE Statement


The Select…Case statement is similar to the If...then…Else statement. The only difference
between the two is that If and ElseIf can evaluate different expressions in each statement,
whereas the select statement can evaluate only one expression. The select statement then uses the
result of this expression to execute different sets of statements. However, select …case is
preferred over If…Elseif when multiple conditions are used because it makes the code easy to
read and understand. The syntax is:
Select Case expression
Case Expressionlist
Statement(s)
.
.
Case Else
Statement(s)
End Select

By Daniel Wainaina @2016 16


VB.NET

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

By Daniel Wainaina @2016 17


VB.NET

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:

i. Do While| Until Condition ii. Do


Statement(s) Statement(s)
Loop Loop While| Until Condition
Or
NB: While | Until are keywords used to repeat the loop and each should be used at a time (Not
both). While repeats the loop until the condition becomes false while Until repeats the loop
until condition becomes true. If While | Until is placed after Loop Statement as shown in syntax
(ii) above, the loop is executed at least once. Exit Do statement can be used to exit the Do loop,
resulting in execution of statements following the Loop statement.

For example, consider a program that prints integers in the range 1 to 10. It can be written in
either of the following forms;

1 a) Dim i As Integer = 1 b) Dim i As Integer = 1


Do Do While (i <= 10)
Console.WriteLine(i) Console.WriteLine(i)
i += 1 i += 1
Loop While (i <= 10) Loop
Console.ReadLine() Console.ReadLine()

By Daniel Wainaina @2016 18


VB.NET

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()

By Daniel Wainaina @2016 19


VB.NET

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

By Daniel Wainaina @2016 20


VB.NET

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

If vote = "F" Then


F = F + 1
End If
If vote = "B" Then
B = B + 1
End If
If vote = "A" Then
A = A + 1
End If
If vote = "S" Then
S = S + 1
End If

Loop While Not (vote = "Q")


Console.WriteLine("Soccer: " & F)
Console.WriteLine("Swimming: " & S)
Console.WriteLine("Athletics: " & A)
Console.WriteLine("Badminton: " & B)
If F > A And F > B And F > S Then
Console.WriteLine("The favourite game is Soccer")
ElseIf B > F And B > S And B > A Then
Console.WriteLine("The favourite game is Badminton")
ElseIf S > F And S > B And S > A Then
Console.WriteLine("The favourite game is Swimming")
ElseIf A > F And A > S And A > B Then
Console.WriteLine("The favourite game is Athletics")
Else
Console.WriteLine("hard to determine")
End If

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

By Daniel Wainaina @2016 21


VB.NET

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.

By Daniel Wainaina @2016 22


VB.NET

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

By Daniel Wainaina @2016 23


VB.NET

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

Similarly, user input can be captured as shown below.


Dim arr(2, 3) As Integer
Dim i As Integer
Dim j As Integer

By Daniel Wainaina @2016 24


VB.NET

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:

By Daniel Wainaina @2016 25


VB.NET

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

Consider the following application,


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()
ReDim arr(5)
For i = LBound(arr) To UBound(arr)
Console.WriteLine("Enter value for element: " & (i + 1))
arr(i) = Console.ReadLine()
Next
Console.WriteLine("Output after redefinition")
For i = LBound(arr) To UBound(arr)
Console.Write(arr(i) & " ")
Next
Console.ReadLine()
End Sub

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()

By Daniel Wainaina @2016 26


VB.NET

ReDim Preserve arr(5)


Console.WriteLine("Output after redefinition")
For i = LBound(arr) To UBound(arr)
Console.Write(arr(i) & " ")
Next
Console.ReadLine()
End Sub

The output is:

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

Then the output would be;

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()

By Daniel Wainaina @2016 27


VB.NET

Next i
Console.ReadLine()
End Sub

3) A company distributes 10 different items around Nairobi through its 5 salesmen.


Using arrays, write a VB.NET program to input the name of the salesman and the
corresponding sales made by each of the salesmen for each of the item. The program
should then compute the total sales for each salesman and the grand sales total for all
the salesmen, and output these alongside the name and sales made by each salesman
(10 marks).
Solution
Sub Main()
Dim Names(2) As String, Sales(2, 3) As Integer
Dim Total As Integer, GrandTotal As Integer
Dim I As Integer, J As Integer
'Input sales values
For I = LBound(Sales, 1) To UBound(Sales, 1)
Names(I) = InputBox("Enter the salesman's name")
For J = LBound(Sales, 2) To UBound(Sales, 2)
Sales(I, J) = InputBox("Enter the sales for item:"
& J)
Next J
Next I
'Compute and display sales details
For I = LBound(Sales, 1) To UBound(Sales, 1)
Console.Write(Names(I))
Total = 0
For J = LBound(Sales, 2) To UBound(Sales, 2)
Console.Write(vbTab & Sales(I, J))
Total = Total + Sales(I, J)
Next J
Console.Write(vbTab & "Total Sales = " & Total)
GrandTotal = GrandTotal + Total
Console.WriteLine()
Next I
Console.WriteLine("The Grand Total is:" & GrandTotal)
Console.ReadLine()
End Sub
4) A meteorologist friend of yours has to take three readings of air humidity a day
(morning, midday and evening), Monday to Friday. Write a program that allows the
user to enter the day of the week and the readings. It should then calculate and display
the day and the day’s average for each of the days of the week as well as the week’s
average using a suitable format.
5) Write a program that reads the student name and marks scored in five subjects by ten
students in a class and stores them in to two arrays. Your program should then
compute the average mark for each student, and then it displays the student name,
marks and the average mark for each student.

By Daniel Wainaina @2016 28


VB.NET

5. FUNCTIONS, CLASSES AND OOP IN VB.NET


FUNCTIONS
Functions provide a better approach to writing applications by dividing the application into a
number of blocks that form together one application. Functions can be seen as small or mini-
programs that each is designed to address a simple problem. VB.NET provide procedures that
give one ability to logically group code that will perform certain tasks. These procedures are
further broken into two types, namely;
i. Sub procedure: perform a specific task but do not return a value to the calling
statement.
ii. Function procedure: perform a specific task and return a value to the calling
statement.
Procedures offer the following benefits
 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.

By Daniel Wainaina @2016 29


VB.NET

 Work can be subdivided among several programmers – team of developers may


subdivide development tasks and later integrate the work, thus reducing development
time.
Procedures are created within a class or a module but not inside another sub or function. A
procedure can be called from the same class or module in which it was created or from
different classes or modules depending on the access modifier used when creating the
procedure. Access modifiers determine the scope within which a procedure can be called.
Sub Procedures
A sub procedure can be created in a module or a class. The default access modifier is public,
indicating that the sub procedure can be called from anywhere in an application. The syntax
for creating a sub procedure is:
[access modifier] Sub procedure-name (argument-list(optional))
Statements
End Sub
NB: In this syntax:
 If no access modifier is specified, Public is used by default.
 Sub keyword indicates that the procedure is a Sub procedure.
 Argument –list represents the arguments to be passed to the procedure. If no
arguments are passed, the sub name must include an empty set of parentheses.
 End Sub keywords indicates the end of the sub procedure.
For example, consider the following procedure that prompts the user to enter the radius of a
circle, then computes and displays the area.
Public Sub compute_area()
Dim radius, area As Double
Const PI As Double = 3.142
radius = CDbl(InputBox("Enter the radius"))
area = PI * (radius ^ 2)
MsgBox("The area of a Circle of radius: " & radius & " is: " & area)
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()

Arguments and arguments passing mechanisms to procedures

By Daniel Wainaina @2016 30


VB.NET

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"))

By Daniel Wainaina @2016 31


VB.NET

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 sub procedure to get length and width of the rectangle


Sub getdetails()
Console.WriteLine("enter length of the rectangle")
length = Console.ReadLine()
Console.WriteLine("enter width of the rectangle")
width = Console.ReadLine()
End Sub

'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

By Daniel Wainaina @2016 32


VB.NET

perimeter = (len + wid) * 2


Return perimeter
End Function

'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

'main procedure that calls both sub procedures


Sub Main()
getdetails()
displaydetails()
Console.ReadLine()
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.

By Daniel Wainaina @2016 33


VB.NET

Public Class Person


'class fields
Private First_name As String
Private Second_name As String
Private dateofbirth As Date
Private address As String

'methods and implementation goes here


End Class

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

Private first_name As String

Private age As Integer

Public Property FirstName()

Get

Return first_name

End Get

Set(ByVal value)

first_name = value

End Set

By Daniel Wainaina @2016 34


VB.NET

End Property

Public Property Personage()

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

By Daniel Wainaina @2016 35


VB.NET

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)

By Daniel Wainaina @2016 36


VB.NET

Console.WriteLine("Last Name:" & Lastname)


Console.WriteLine("Address:" & address)
Console.WriteLine("Phone Number:" & Phonenumber)
End Sub
End Class

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

By Daniel Wainaina @2016 37


VB.NET

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

Using the derived class


Derived class can be used without even knowing that it derives from another class. However,
being aware of the inheritance relationship between two classes helps in writing more flexible
code. For example, Employee class can be instantiated and fields used as shown below.
Dim emp1 As Employee = New Employee()
emp1.Sname = "John"
emp1.Fname = "William"
'
'

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

‘an object cannot be created from 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

A derived class cannot be generated from such as a class.


Polymorphism
This is an OOP concept that provide capability to have methods and properties in multiple
classes that have the same name and use them interchangeably, even though each class
implement the same methods or properties in different ways. To implement polymorphism,
keywords such as Overridable, Overrides, NotOverridable, and MustOverride are used.
(Refer their meaning from polymorphism in OOP definitions).

By Daniel Wainaina @2016 38


VB.NET

Polymorphism is commonly implemented through overloading and overriding.


Overriding is a feature through which existing methods get a new implementation. Methods
with same name and signature but performing different tasks.
For example, in the code below, method print() is defined in Class person and inherited by
class Student which implements it differently.
Public Class Person
Public Fname As String
Public Sname As String

Public Overridable Function print() As String


Dim completename As String
completename = Fname & " " & Sname
Return completename
End Function

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

Overloading is a feature that allow existence of multiple methods, constructors, or properties


that have the same name but different parameter lists. To overload a method, you simply
define two or more methods with same name but different parameters using the Overloads
keyword.
For example, in the class Addition below, method Add() is overloaded to compute sum of
different integers. NB: the first Add sums two integers and second Add sums three integers.
Public Class Addition
Public sum As Integer
Public Overloads Function Add(ByVal num1 As Integer, ByVal num2 As
Integer) As Integer
sum = num1 + num2
Return sum
End Function
Public Overloads Function Add(ByVal num1 As Integer, ByVal num2 As
Integer, ByVal num3 As Integer) As Integer
sum = num1 + num2 + num3
Return sum
End Function

End Class

They can be called as follows;


Dim ad As Addition = New Addition()
Dim sum1, sum2 As Integer
sum1 = ad.Add(2, 3) ‘ takes two parameters
sum2 = ad.Add(2, 3, 4) ‘ takes three parameters
MsgBox("Function 1 sum is:" & sum1 & " " & "Function 2 sum is:" &
sum2)

By Daniel Wainaina @2016 39


VB.NET

By Daniel Wainaina @2016 40

You might also like