Chapter 3
Chapter 3
Chapter 3
NET
Introduction
VB.Net is an object-oriented programming language. In Object-Oriented Programming methodology, a
program consists of various objects that interact with each other by means of actions. The actions
that an object may take are called methods. Objects of the same kind are said to have the same type or, more
often, are said to be in the same class.
When we consider a VB.Net program, it can be defined as a collection of objects that communicate via
invoking each other's methods. Let us now briefly look into what do class, object, methods, and instant
variables mean.
Object - Objects have states and behaviors. Example: A dog has states -color, name, breed as well
as behaviors - wagging, barking, eating, etc. An object is an instance of a class.
Class - A class can be defined as a template/blueprint that describes the behaviors/states that object
of its type support.
Methods - A method is basically a behavior. A class can contain many methods. It is in methods
where the logics are written, data is manipulated and all the actions are executed.
Instant Variables - Each object has its unique set of instant variables. An object's state is created by
the values assigned to these instant variables.
What are the basic OOP terminologies?
Identifiers
Identifiers are names given to namespaces, types (enumerations, structures, classes, standard modules,
interfaces, and delegates), type members (methods, constructors, events, constants, fields, and properties),
and variables. Identifiers must begin with either an alphabetic or underscore character (_), may be of any
length, and after the first character must consist of only alphanumeric and underscore characters.
Namespace declarations may be declared either with identifiers or qualified identifiers. Qualified identifiers
consist of two or more identifiers connected with the dot character (.) Only namespace declarations may
use qualified identifiers.
Consider this code fragment:
Imports System
Namespace ORelly.ProgVBNet
Public Class Hello
Public Shared Sub SayHello( )
Console.WriteLine("hello, world")
End Sub
End Class
End Namespace
This code fragment declares three identifiers: OReilly.ProgVBNet (a namespace name), Hello (a class
name), and SayHello (a method name). In addition to these, the code fragment uses three identifiers
Declared elsewhere: System (a namespace name), Console (a class name), and WriteLine (a method name).
Although Visual Basic .NET is not case sensitive, the case of identifiers is preserved when applications are
compiled. When using Visual Basic .NET components from case-sensitive languages, the caller must use
the appropriate case.
The basic rules for naming classes in VB.Net are as follows:
A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or
underscore. The first character in an identifier cannot be a digit.
It must not contain any embedded space or symbol like? - +! @ # % ^ & ( ) [ ] { } . ; : " ' / and \.
However, an underscore ( ) can be used.
It should not be a reserved keyword.
1|Page
Keywords
Keywords are words with special meaning in a programming language. In Visual Basic .NET, keywords
are reserved; that is, they cannot be used as tokens for such purposes as naming variables and subroutines.
addHandler, addressOf, Allas, And, Andalso, As Boolean, ByRef, Byte, BayVal, Call, Case, Catch,
CBool,and, if , for……. (Please refer more VB.Net reserved key words)
Data Types
Types in Visual Basic .NET are divided into two categories: value types and reference types. Value types
minimize memory overhead and maximize speed of access, but they lack some features of a fully object-
oriented design (such as inheritance). Reference types give full access to object-oriented features, but they
impose some memory and speed overhead for managing and accessing objects. When a variable holds a
value type, the data itself is stored in the variable. When a variable holds a reference type, a reference to
the data (also known as a pointer) is stored in the variable, and the data itself is stored somewhere else.
Visual Basic .NET's primitive types include both value types and reference types (see "Fundamental Types"
in this section.
Data types refer to an extensive system used for declaring variables or functions of different types. The type
of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted.
Data Types Available in VB.Net
VB.Net provides a wide range of data types. The following table shows all the data types available:
Object 4 bytes on 32-bit platform Any type can be stored in a variable of type Object
2|Page
1.401298E-45 through 3.4028235E+38 for positive values
User-Defined Depends on implementing platform Each member of the structure has a range determined by its data type
and independent of the ranges of the other members
CBool(expression)
1
Converts the expression to Boolean data type.
CByte(expression)
2
Converts the expression to Byte data type.
CChar(expression)
3
Converts the expression to Char data type.
CDate(expression)
4
Converts the expression to Date data type
CDbl(expression)
5
Converts the expression to Double data type.
CDec(expression)
6
Converts the expression to Decimal data type.
CInt(expression)
7
Converts the expression to Integer data type.
CLng(expression)
8
Converts the expression to Long data type.
CObj(expression)
9
Converts the expression to Object type.
CSByte(expression)
10
Converts the expression to SByte data type.
CShort(expression)
11
Converts the expression to Short data type.
CSng(expression)
12
Converts the expression to Single data type.
CStr(expression)
13
Converts the expression to String data type.
Example:
The following example demonstrates some of these functions:
Module DataTypes
Sub Main()
Dim n As Integer
3|Page
Dim da As Date
Dim bl As Boolean = True
n = 1234567
da = Today
Console.WriteLine(bl)
Console.WriteLine(CSByte(bl))
Console.WriteLine(CStr(bl))
Console.WriteLine(CStr(da))
Console.WriteLine(CChar(CChar(CStr(n))))
Console.WriteLine(CChar(CStr(da)))
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
True
-1
True
12/4/2012
1
1
Variables
A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable
in VB.Net has a specific type, which determines the size and layout of the variable's memory; the range of
values that can be stored within that memory; and the set of operations that can be applied to the variable.
We have already discussed various data types. The basic value types provided in VB.Net can be categorized
as:
Type Example
Integral types SByte, Byte, Short, UShort, Integer, UInteger, Long, ULong
Floating point types Single and Double
Decimal types Decimal
Boolean types True or False values, as assigned
Date types Date
SCOPE AND DURATION:
The scope and duration of a variable is determined by the keywords Dim, Redim, Static, Public or
Private. Whilst declarations can appear anywhere within the body of code.
4|Page
Variable Naming Rules:
Must begin with a letter.
Can't contain an embedded period or embedded type-declaration character.
Must not exceed 255 characters.
Must be unique within the same scope, which is the range from which the variable can be
referenced — a procedure, a form, and so on.
Variable Declaration in VB.Net
The Dim statement is used for variable declaration and storage allocation for one or more variables. The
Dim statement is used at module, class, structure, and procedure or block level.
Each variable in the variable list has the following syntax and parts:
variablename[ ( [ boundslist ] ) ] [ As [ New ] datatype ] [ = initializer ]
variablename: is the name of the variable
boundslist: optional. It provides list of bounds of each dimension of an array variable.
New: optional. It creates a new instance of the class when the Dim statement runs.
datatype: Required if Option Strict is On. It specifies the data type of the variable.
initializer: Optional if New is not specified. Expression that is evaluated and assigned to the
variable when it is created.
Some valid variable declarations along with their definition are shown here:
Dim StudentID As Integer
Dim StudentName As String
Dim Salary As Double
Dim count1, count2 As Integer
Dim status As Boolean
Dim exitButton As New System.Windows.Forms.Button
Dim lastTime, nextTime As Date
Public Class Form1
Dim mm As String
Protected Friend ReadOnly name As String = "Abebe"
Public da As Date
Friend Shadows sex As Char
Variable Initializers
New to Visual Basic .NET is the ability to combine variable declaration and assignment. For example, this
code declares an Integer i and gives it an initial value of 10:
Dim i As Integer = 10
This is equivalent to the following code:
Dim i As Integer
i = 10
Scope
Scope refers to the so-called visibility of identifiers within source code. That is, given a particular identifier
declaration, the scope of the identifier determines where it is legal to reference that identifier in code. For
example, these two functions each declare a variable CoffeeBreaks. Each declaration is invisible to the code
in the other method. The scope of each variable is the method in which it is declared.
Visual Basic .NET doesn't permit the same variable name to be declared at both the method level and the
block level. Further, the life of the block-level variable is equal to the life of the method. This means that if
the block is re-entered, the variable may contain an old value (don't count on this behavior, as it is not
guaranteed and is the kind of thing that might change in future versions of Visual Basic).
Statements
A statement is a complete instruction in Visual Basic programs. It may contain keywords, operators,
variables, literal values, constants and expressions.
5|Page
Statements could be categorized as:
Declaration statements - these are the statements where you name a variable, constant, or
procedure, and can also specify a data type.
Executable statements - these are the statements, which initiate actions. These statements can call
a method or function, loop or branch through blocks of code or assign values or expression to a
variable or constant. In the last case, it is called an Assignment statement.
Branching Statements
Visual Basic .NET supports a number of branching statements that interrupt the sequential flow of program
execution and instead allow it to jump from one portion of a program to another. These can be either
conditional statements (such as If or Select Case) or unconditional (such as Call and Exit).
Call
The Call statement invokes a subroutine or function. For example:
Call SomeMethod( )
When the invoked subroutine or function finishes, execution continues with the statement following the
Call statement. If a function is invoked, the function's return value is discarded.
The Call statement is redundant because subroutines and functions can be invoked simply by naming them:
SomeMethod( )
Exit
The Exit statement causes execution to exit the block in which the Exit statement appears. It is generally
used to prematurely break out of a loop or procedure when some unusual condition occurs. The Exit
statement should be avoided when possible because it undermines the structure of the block in which it
appears. For example, the exit conditions of a For loop should be immediately apparent simply by looking
at the For statement. It should not be necessary to read through the entire loop to determine if there are
additional circumstances under which the loop might exit. If a given For loop truly needs an Exit statement,
investigate whether a different loop construct would be better suited to the task. If a given procedure truly
needs an Exit statement, investigate whether the procedure is factored appropriately. The Exit statement
has a different form for each type of block in which it can be used, as listed here:
Exit Do:-Exits a Do loop. Execution continues with the first statement following the Loop statement.
Exit For:-Exits a For loop. Execution continues with the first statement following the Next statement.
Exit Function:-Exits a function. Execution continues with the first statement following the statement that
called the function.
Exit Property:-Exits a property get or property set procedure. Execution continues with the first statement
following the statement that invoked the property get or property set procedure.
Exit Sub:-Exits a subroutine. Execution continues with the first statement following the statement that
called the subroutine.
Exit Try:-Exits the Try clause of a Try block. If the Try block has a Finally clause, execution continues
with the first statement in the Finally clause. If the Try block does not have a Finally clause, execution
continues with the first statement following the Try block.
1. Goto
The Goto statement transfers execution to the first statement following the specified label. For example:
The Goto statement transfers execution to the first statement following the specified label. For example:
' ...
Goto MyLabel
' ...
MyLabel:
' ...
The label must be in the same procedure as the Goto statement.
6|Page
The Goto statement is generally avoided in structured programming because it often leads to code that is
difficult to read and debug.
2. If
The If statement controls whether a block of code is executed based on some condition. The simplest form
of the If statement is:
If expression Then
Statements
End If
expression is any expression that can be interpreted as a Boolean value. If expression is True, the statements
within the If block are executed. If expression is False, those statements are skipped.
To provide an alternative set of statements to execute when expression is False, add an Else
clause, as shown here:
If expression Then
statements
Else
statements
End If
If expression is True, only the statements in the If clause are executed. If expression is False, only the
statements in the Else clause are executed. Finally, a sequence of expressions can be evaluated by including
one or more ElseIf clauses, as shown here:
If expression Then
statements
ElseIf expression Then
statements
ElseIf expression Then
statements
Else
statements
End If
The first If or ElseIf clause whose expression evaluates to True will have its statements executed. Statements
in subsequent ElseIf clauses will not be executed, even if their corresponding expressions are also True. If
none of the expressions evaluate to True, the statements in the Else clause will be executed. The Else clause
can be omitted if desired. Example for if else and ElseIf
Imports System.Console
Imports System.Console Module Module1
Module Module1 Sub Main()
Sub Main() Dim Mark As Integer
Dim num As Integer WriteLine("Enter Mark")
WriteLine("Enter Number") Mark = ReadLine()
num = ReadLine() If Mark > 70 And Mark <= 100 Then
If num Mod 2 = 0 Then Console.WriteLine("Your Grade is A")
Console.WriteLine(num & " is even number.") ElseIf Mark > 50 Then
Else Console.WriteLine("Your Grade is B")
Console.WriteLine(num & " is Odd number.") Else
End If Console.WriteLine("Your Grade is F")
ReadLine() End If
End Sub ReadLine()
End Sub
End Module
7|Page
3. Select Case
The Select Case statement chooses a block of statements to execute based on some value. For example:
Select Case strColor
Case "red"
' ...
Case "green"
' ...
Case "blue"
' ...
Case "yellow"
' ...
Case Else
' ...
End Select
If strColor in this example contains "blue", only the statements in the Case "blue" clause are executed. If
none of the Case clauses matches the value in the Select Case statement, the statements in the Case Else
clause are executed. If more than one Case clause matches the given value, only the statements in the first
matching Case clause are executed.
Case statements can include multiple values to be matched against the value given in the Select
Case statement.
Loops and arrays
There may be a situation when you need to execute a block of code several number of times. In general,
statements are executed sequentially: The first statement in a function is executed first, followed by the
second, and so on. Programming languages provide various control structures that allow for more
complicated execution paths. A loop statement allows us to execute a statement or group of statements
multiple times and following is the general form of a loop statement in most of the programming
languages:
VB.Net provides following types of loops to handle looping requirements. Click the following links to
check their details.
8|Page
Loop Control Statements:
Loop control statements change execution from its normal sequence. When execution leaves a scope, all
automatic objects that were created in that scope are destroyed.VB.Net provides the following control
statements. Click the following links to check their details.
Control Statement Description
Terminates the loop or select case statement and transfers execution
Exit statement
to the statement immediately following the loop or select case.
Causes the loop to skip the remainder of its body and immediately
Continue statement
retest its condition prior to reiterating.
Transfers control to the labeled statement. Though it is not advised to
GoTo statement
use GoTo statement in your program.
It repeats the enclosed block of statements while a Boolean condition is True or until the condition
becomes True. It could be terminated at any time with the Exit Do statement.
2 Do Loop
The formats are
a) Do While condition
Block of one or more VB statements
Loop
b) Do
Block of one or more VB statements
Loop While condition
c) Do Until condition
Block of one or more VB statements
Loop
d) Do
Block of one or more VB statements
Loop Until condition
* Exiting the Loop
Sometime we need exit to exit a loop prematurely because of a certain condition is
fulfilled. The syntax to use is known as Exit Do. Let’s examine the following example
Example (a)
Do while counter <=1000
TextBox1.Text=counter
counter +=1
Loop
* The above example will keep on adding until counter >1000.
The above example can be rewritten as
Do
TextBox1.Text=counter
counter+=1
Loop until counter>1000
Example (b)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
9|Page
Dim sum, n As Integer
Do
n += 1
sum += n
ListBox1.Items.Add(n & vbTab & sum)
If n = 100 Then
Exit Do
End If
Loop Sub
In the above Example, we find the summation of 1+2+3+4+……+100. In the design stage, you need to
insert a ListBox into the form for displaying the output, named List1. The program uses the Add method
to populate the ListBox. The statement ListBox1.Items.Add(n & vbTab & sum) will display the headings
in the ListBox, where it uses the vbTab function to create a space between the headings n and sum.
The format is: For counter=startNumber to endNumber (Step increment) One or more VB statements
Next Sometimes the user might want to get out from the loop before the repetitive process is completed.
The command to use is Exit For. To exit a For...Next Loop, you can place the Exit For statement within
the loop; and it is normally used together with the If…..Then… statement. For its application, you can
refer to Example.
Example C
Dim counter as Integer
For counter=1 to 10
ListBox1.Items.Add (counter)
Next
* The program will enter number 1 to 10 into the Listbox.
Example D
Dim counter, sum As Integer
For counter=1 to 100 step 10
sum+=counter
ListBox1.Items.Add (sum)
Next
* The program will calculate the sum of the numbers as follows:
sum=0+10+20+30+40+......
Example E
Dim counter, sum As Integer
sum = 1000
For counter = 100 To 5 Step -5
sum - = counter
ListBox1.Items.Add(sum)
Next
*Notice that increment can be negative. The program will compute the subtraction as follows: 1000-100-
95-90-..........
Example F
Dim n as Integer
For n=1 to 10
If n>6 then
Exit For
End If
Else
10 | P a g e
ListBox1.Items.Add ( n)
Next
End If
Next
The process will stop when n is greater than 6.
The structure of a While….End While is very similar to the Do Loop. It takes the following format:-
While condition
Statements
End While
The above loop means that the loop will end when the condition is met.
Example G
Dim sum, n As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim sum, n As Integer
While n <> 100
n += 1
sum = sum + n
ListBox1.Items.Add(n & vbTab & sum)
End While
End Sub
Events
Events are basically a user action like key press, clicks, mouse movements, etc…, or some occurrence like
system generated notifications. Applications need to respond to events when they occur.
Clicking on a button, or entering some text in a text box, or clicking on a menu item, all are examples of
events.
An event is an action that calls a function or may cause another event.
Event handlers are functions that tell how to respond to an event.
VB.Net is an event-driven language. There are mainly two types of events:
Mouse events
Keyboard events
Handling Mouse Events
Mouse events occur with mouse movements in forms and controls. Following are the various mouse events
related with a Control class:
MouseDown - it occurs when a mouse button is pressed
MouseEnter - it occurs when the mouse pointer enters the control
MouseHover - it occurs when the mouse pointer hovers over the control
MouseLeave - it occurs when the mouse pointer leaves the control
MouseMove - it occurs when the mouse pointer moves over the control
MouseUp - it occurs when the mouse pointer is over the control and the mouse button is released
MouseWheel - it occurs when the mouse wheel moves and the control has focus
The event handlers of the mouse events get an argument of type MouseEventArgs. The MouseEventArgs
object is used for handling mouse events. It has the following properties:
Buttons - indicates the mouse button pressed
Clicks - indicates the number of clicks
Delta - indicates the number of detents the mouse wheel rotated
Handling Keyboard Events
Following are the various keyboard events related with a Control class:
11 | P a g e
KeyDown - occurs when a key is pressed down and the control has focus
KeyPress - occurs when a key is pressed and the control has focus
KeyUp - occurs when a key is released while the control has focus
The event handlers of the KeyDown and KeyUp events get an argument of type KeyEventArgs. This
object has the following properties:
Alt - it indicates whether the ALT key is pressed/p>
Control - it indicates whether the CTRL key is pressed
Handled - it indicates whether the event is handled
KeyCode - stores the keyboard code for the event
KeyData - stores the keyboard data for the event
KeyValue - stores the keyboard value for the event
Modifiers - it indicates which modifier keys (Ctrl, Shift, and/or Alt) are pressed
Shift - it indicates if the Shift key is pressed
The event handlers of the KeyDown and KeyUp events get an argument of type KeyEventArgs. This
object has the following properties:
Handled - indicates if the KeyPress event is handled
KeyChar - stores the character corresponding to the key pressed
Classes
A class definition starts with the keyword Class followed by the class name; and the class body, ended by
the End Class statement.
A class is one form of data type. As such, a class can be used in contexts where types are expected—in
variable declarations, for example. In object-oriented design, classes are intended to represent the definition
of real-world objects, such as customer, order, product, etc. The class is only the definition, not an object
itself. An object would be a customer, an order, or a product. A class declaration defines the set of
members—fields, properties, methods, and events—that each object of that class possesses. Together, these
members define an object's state, as well as its functionality. An object is also referred to as an instance of
a class. Creating an object of a certain class is called instantiating an object of the class.
Consider the class definition in the following Example:-
Public Class Employee
Public EmployeeNumber As Integer
Public FamilyName As String
Public GivenName As String
Public DateOfBirth As Date
Public Salary As Decimal
Public Function Format( ) As String
Return GivenName & " " & FamilyName
End Function
End Class
The code in the above Example defines a class called Employee. It has five public fields (also known as
data members) for storing state, as well as one member function. The class could be used as shown in the
following Example
‘’ Using a class
Dim emp As New Employee( )
emp.EmployeeNumber = 10
emp.FamilyName = "Rodriguez"
emp.GivenName = "Celia"
emp.DateOfBirth = #1/28/1965#
emp.Salary = 115000
12 | P a g e
Console.WriteLine("Employee Name: " & emp.Format( ))
Console.WriteLine("Employee Number: " & emp.EmployeeNumber)
Console.WriteLine("Date of Birth: " & emp.DateOfBirth.ToString("D",
Nothing))
Console.WriteLine("Salary: " & emp.Salary.ToString("C", Nothing))
13 | P a g e
Protected width As Integer
Protected height As Integer
Public Sub setWidth(ByVal w As Integer)
width = w
End Sub
Public Sub setHeight(ByVal h As Integer)
height = h
End Sub
End Class
' Derived class
Class Rectangle : Inherits Shape
Public Function getArea() As Integer
Return (width * height)
End Function
End Class
Class RectangleTester
Shared Sub Main()
Dim rect As Rectangle = New Rectangle()
rect.setWidth(5)
rect.setHeight(7)
' Print the area of the object.
Console.WriteLine("Total area: {0}", rect.getArea())
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces the following result: Total area: 35
Base Class Initialization
The derived class inherits the base class member variables and member methods. Therefore, the super class
object should be created before the subclass is created. The super class or the base class is implicitly known
as MyBase in VB.Net.
14 | P a g e