You are on page 1of 32

Language Fundamentals part 2

VB .NET Programming

Contents
Arrays?
Using Arrays
Using Classes
Events and Event Handlers
Exceptions and Exception Handling
Coding Conventions

Objectives
At the end of this module you should be able to:

Define an array

Describe different ways to declare an array

Describe different ways to create an array

Describe different ways to initialize an array

Utilize methods for manipulating an array

Demonstrate a single-dimensional array

Demonstrate a multi-dimensional array

Demonstrate a jagged array (array of arrays)

Describe stacks

Describe queues

What is an Array?
An array is a data structure that
contains a number of variables,
which are accessed through
computed indices.
The variables contained in an array,
are called the elements of the array.
They must all be of the same type,
and this type is called the element
type of the array.
Dim numbers() as Integer

A one-dimensional
array on the heap
Values
The
heap

Int() numbers object


Indices

Identifier
name
Indexing
operator

type

Dim numbers() as Integer


numbers

= new int(4)
4

Creating an Array
There are three steps to create an array:

1. Declaration

2. Construction / Creation

3. Initialization

Public Class ArrayTest


Public Shared Sub Main(ByVal args As
String())
Dim scores As Integer()
scores = New Integer(2) {}
scores(0) = 10
scores(1) = 7
scores(2) = 9
End Sub
End Class

Creating an Array Initialization


Initializing an array means assigning values to its elements:
Public Class ArrayTest
Public Shared Sub Main(ByVal args As
String())

Array index starts with 0

Declaration, construction and


initialization at the same
time

Dim numbers As Integer()


Dim letters As Char(), symbols As
Char()
Dim countries As String()
numbers = New Integer(2) {}
Dim currencies As String() = New
String(2) {}
numbers(0) = 100
numbers(1) = 200
numbers(2) = 300
Dim newNumbers As Integer() = {1, 2,
3}
End Sub
End Class

Manipulating Arrays
The following are methods for
manipulating arrays:

Length gives the size of the array

Printing each element of an array

Assigning array to another array

Passing array to a method

Passing anonymous array

Sample Output:
100
200
300
6
6

Public Class ArrayTest


Public Shared Sub Main(ByVal args As String())
Dim numbers As Integer() = New Integer(2) {}
numbers(0) = 100
numbers(1) = 200
numbers(2) = 300
Dim newNumbers As Integer() = {1, 2, 3}
For i As Integer = 0 To numbers.Length - 1
System.Console.WriteLine(numbers(i))
Next
numbers = newNumbers
sumNumbers(numbers)
sumNumbers(New Integer() {3, 2, 1})
End Sub
Private Shared Sub sumNumbers(ByVal n As Integer())
Dim sum As Integer = 0
For i As Integer = 0 To n.Length - 1
sum += n(i)
Next

System.Console.WriteLine(sum)
End Sub
End Class

Single-Dimensional Arrays
Single-Dimensional Arrays

Are declared as

Can also be initialized as

Dim numbers As Integer()


numbers = New Integer(3)

dim myStringArray as string()= new


string()
{Sun,Sat,Mon,Tue,wed,Fri};

Note: You can also omit the new operator from the above example. You can
assign these values directly without using the new operator.
dim myStringArray as string()=
{Sun,Sat,Mon,Tue,wed,Fri};
8

Multi-Dimensional Arrays
Multi-Dimensional Arrays

Are declared as

Dim numbers as
integer(,)
numbers = new
integer(4,2)
Two-Dimensional Arrays

Can also be initialized as


Dim numbers as integer(,) =
new integer[4,2]
{{1,2},{3,4},{5,6},{7,8}};
Two-Dimensional Arrays

Classes
A blueprint of an object
A class acts as the template from which an instance of an object is
created. The class defines the properties of the object and the
methods used to control the object's behavior.
VB.Net uses classes to do specific tasks
E.g. Console

All datatypes are classes in .Net

10

Instantiating a Class & Accessing its Members

Instantiating a class means


creating objects of its own
type.
The new operator is used to
instantiate a class.
Accessing members of the
class is done by .
Public Class Program
Private Shared dog As Dog
Public Shared Sub Main()
dog = new Dog(Jager)
dog.Bark()
Console.Read()
End Sub
End Class

Public Class Dog


Protected _name As String
Public Event HasBarked(ByVal name As String)
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Public Sub Bark()
Console.Writeline("Arf! Arf!")
RaiseEvent HasBarked(Me.Name)
End Sub
Public Sub New()
End Sub
Public Sub New(ByVal name As String)
_name = name
End Sub
End Class

11

Class

Made up of at least one of the


following:

Variables
Methods
Properties
Events

These are called members

Public Class Dog


Protected _name As String
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property

Public Sub Bark()


Console.Write("Arf! Arf!")
End Sub
End Class

12

Class Members

A class member refers to one of


the fields or methods of a class.

Instance members are variables


and methods belonging to objects
where a copy of each variable and
method is created for each object
instantiated.

Shared members are variables and


methods belonging to a class
where only a single copy of
variables and methods are shared
by each object

Constant is a class member that


represents a constant value: a
value that can be computed at
compile-time.

Public Class TestStatic


'instance member variable
Public length As Integer, breadth As Integer
'instance static member variable
Public Shared count As Integer
'instance member method
Public Function GetData(ByVal p As Integer, ByVal q
As Integer) As Integer
Dim totalarea As Integer = p * q
Return totalarea
End Function
'static member method.
Public Shared Function AddData(ByVal m As Integer,
ByVal n As Integer) As Integer
Dim totalarea As Integer = m * n
Return totalarea
End Function
End Class

13

Class Modifiers
Modifiers change the way a class can be used
Access modifiers control the accessibility of a class
Modifier
public

Description

protected

Access is limited to the containing class or types


derived from the containing class.

private

Access limited to the containing type.


By default access is private.

Friend

Access limited to this program/assembly.

noninheritable

Class is prevented from inheriting

Must inherit

Class is incomplete and that is intended to be used


as base class.

protected Friend

Available in the containing program or assembly and in


the derived classes.

Access is not limited

14

Member Modifiers
Modifier

Description

Impact on Members

Shadows

Allows you to declare a member with the same


name or signature as an inherited member.

constant, field, property,


event, method, indexer

public

Access is not limited

Field, method, property,


event, indexer

protected

Access is limited to the containing class or


types derived from the containing class

Field, method, property,


event, indexer

protected
internal

Available in the containing program or


assembly and in the derived classes. Includes
both protected and internal modifier.

Field, method, property,


event, indexer

internal

Member is available within the assembly or


component that is being created but not to the
clients of that component

Field, method, property,


event, indexer

private

Access limited to the containing type. By


default is access is private.

Field, method, property,


event, indexer
15

Member Modifiers (Continued)


Modifier

Description

Impact on Members

MustInhe
rit

Is intended to be used as base class and the


class itself is incomplete

method, property, event,


indexer

Shared

Does not operate on a specific instance of a


member

field, method, property,


event, constant, indexer

readonly

Assignments to the fields can only occur in


the declaration or in the same class
constructor

Field, Property

NotInher
atable

Specify that a member cannot be inherited.

method, property, event,


indexer

WriteOnl
y

Reading the value of the property is


prohibited.

Property

16

Member Modifiers (Continued)


Modifier

Description

Impact on Member

overrides

Provide a new implementation of a virtual


member inherited from a base class or
Provide an implementation of an abstract
member inherited from an abstract class

Method, property, event,


indexer

17

Shared Members
The Keyword Shared is used when the member of the class is
common among all instances of the class.
Public Class Dog
Protected _name As String
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Public Sub Bark()
Console.Write("Arf! Arf!")
End Sub
Public Shared _species As String
End Class

Public Class Program


Shared Sub main()
Dim dog1 As New Dog
Dim dog2 As New Dog
dog1._species = "shitzu"
Console.WriteLine(dog1._species)
dog2._species = "Bulldog"
Console.WriteLine(dog1._species)
End Sub
End Class

Output:

18

What is a Method?
A method is a portion of code referring to behaviors associated
either with an object or its class
It is used to access and process data contained in the object
It is also used to provide responses to any messages received from other
objects
It is the executable code that implements the logic of a particular
message for a class

It is an operation or function that is associated with an object and is


allowed to manipulate that object's data

19

Method Types
There are 2 types of Methods
Sub

Does not return a value


Syntax:
[accessor] Sub [Name] (parameters)
method_body
End sub

Functions

Sub AddNumbers(ByVal x As Integer,


ByVal y As Integer)
x+y
End Sub

Function SubtractNumbers(ByVal x As
Integer, ByVal y As Integer) As
Integer
dim difference as integer = x-y
return difference
End Function

Returns a value
Syntax:
[accessor] Function [Name] (parameters) as ReturnType
method_body
End Function

20

Creating a Method
Method declaration consists of five components:

Methods Modifiers (modifiers )


Name of the Method ([name])
Type of value the Method returns (returntype)
List of parameters (parameters)
Body of the Method (method_body)
accessor

21

Creating a Method

Steps in declaring a method:


1. Set the return type
2. Provide method name
3. Declare formal parameters

Method signature
consists of the method name and its
parameters
must be unique for each method in a class

return statement
allows the method to return a value to its
caller
also means to stop the execution of the
current method and return to its caller
implicit return at the end of the method

A method that does not return a value


must specify void as its return type

A method with empty parameters

Class Number
Private Function multiply(ByVal i As
Integer, ByVal j As Integer) As
Integer
Return i * j
End Function
Private Function divide(ByVal i As
Integer, ByVal j As Integer) As
Integer
Return i / j
End Function
Private Sub printSum(ByVal i As
Integer, ByVal j As Integer)
Console.WriteLine(i + j)
End Sub

Private Function getPi() As Double


Return 3.14159265358979
End Function
End Class

22

Method Calling (Invoking)


The process of activating a method is known as invoking or calling
The steps to call a method are:
1. Method name should match
2. Number of parameters should match
3. Type of parameters should match

Ways of calling a method include:


1. Calling a method through its object name
2. Calling a method within the same class
3. Calling a static method through its class name

23

Method Calling
Public Class CSharpMain
Public Shared Sub Main(ByVal args As
String())
' create a Person object
Dim you As New Person()
you.talk()
you.jump(3)
Console.WriteLine(you.tellAge())

'static keyword qualifies the method


CSharpMain.talkOnly(you)
' create object of main program
Dim [me] As New CSharpMain()
[me].jumpOnly(you)
End Sub
Private Shared Sub talkOnly(ByVal p As
Person)
'static method
p.talk()
End Sub
Private Sub jumpOnly(ByVal p As Person)
' method
p.jump(2)
End Sub
End Class

Class Person
Public Sub talk()
Console.WriteLine("blah, blah...")
End Sub

Public Sub jump(ByVal times As Integer)


For i As Integer = 0 To times - 1
Console.WriteLine("whoop!")
Next
End Sub
Public Function tellAge() As String
Return "I'm " + getAge()
End Function
Public Function getAge() As Integer
Return 10
End Function
End Class

blah, blah...
whoop!
whoop!
whoop!
I'm 10
blah, blah...
whoop!
whoop!
24

Method Types
VB.Net employs four kinds of parameters that are passed to methods
Value Type parameters

Used for passing parameters into methods by value


Reference Type parameters

Used to pass parameters into methods by reference


Output parameters

Used to pass results back from a method


Parameter arrays
Used in a method definition to enable it to receive variable
number of arguments when called

25

Passing Value Type Parameters


A value-type variable contains its data directly
By passing a value-type variable to a method which passes a copy of the
variable to the method.
Changing the parameter value inside the method does not change the
original data stored in the variable.
Imports System
Public Class PassingValByVal
Public Shared Sub SquareIt(ByVal x As Integer)
' The parameter x is passed by value.
x *= x
'Changes to x will not affect the original value of x.
Console.WriteLine("The value inside the method: {0}", x)
End Sub

Private Shared Sub Main()


Dim n As Integer = 5
Console.WriteLine("The value inside the method: {0}", x)
SquareIt(n) ' Passing the variable by value.
Console.WriteLine("The value after calling the method: {0}", n)
End Sub
End Class
The value before calling the method: 5
The value inside the method: 25
The value after calling the method: 5
26

Reference Parameters
A variable of a reference type
does not contain its data directly

It contains a reference to its


data
Passing a reference-type
parameter by reference, it is
possible to change the data
pointed to, such as the value of
a class member.

Imports System
Class PassingValByRef
Private Shared Sub SwapByRef(ByRef x As
Integer, ByRef y As Integer)
Dim temp As Integer = x
x = y
y = temp
End Sub
Public Shared Sub Main()
Dim i As Integer = 2
Dim j As Integer = 3
Console.WriteLine("i = {0} j = {1}", i,
j)
SwapByRef(i, j)
Console.WriteLine("i = {0} j = {1}", i,
j)
End Sub
End Class

i=2j=3
i=3j=2

27

Parameter Arrays
The paramarray keyword allows you to specify a method parameter
that takes an argument where the number of arguments is variable.

No additional parameters are permitted after the paramarray keyword


in a method declaration, and only one paramarray keyword is
permitted in a method declaration.

28

Parameter Arrays
Public Class [MyClass]
Public Shared Sub UseParams(ByVal
ParamArray list As Integer())
For i As Integer = 0 To list.Length 1
Console.WriteLine(list(i))
Next
Console.WriteLine()
End Sub
Public Shared Sub UseParams2(ByVal
ParamArray list As Object())
For i As Integer = 0 To list.Length 1
Console.WriteLine(list(i))
Next
Console.WriteLine()
End Sub
End Class

Shared Sub Main()


UseParams(1, 2, 3)
' An array of objects can also be passed,
as long as
UseParams2(1, "a"C, "test")
' the array type matches the method being
called.
Dim myarray As Integer() = New Integer()
{10, 11, 12, 13}
UseParams(myarray)
End Sub

1
2
3

1
a
test
10
11
12
13

29

Properties
Properties are special types of methods.
There are 2 methods for a given property
A Getter

Always returns a value of the type of the property


A Setter

Has one input parameter


The name of the parameter is always value
Programming practice: Properties are always public and variables are
always private or protected.
A property can be readonly or write only.
Protected _name As String
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
30

Key Points
An array is a collection of values (either primitive or objects) all of which
have the same data type

There are 3 steps in creating an array:


Declaration
Creation
Initialization

Array elements are accessed using an index that starts at 0


Length is the property of array that returns its size (i.e., number of
elements)
Arrays can be passed to methods or assigned to variables

Classes are the basic blue print of every application.


All members of a class that can be accessed is limited by an accessor
Methods give objects their behavioral characteristics
A method must have a return type, a name, and optional parameters
The method signature refers to a method name and its parameters
31

Key Points
Return statement returns a value to its caller or returns control to its
caller
A method that does not return a value must specify void as a return
type
Calls to a method should match its method signature
When calling a method in the same class, use only the method name
(Nested Methods)
When calling a method outside class, use the object reference
When calling a shared method, use the class name
In vb.NEt method parameters are passed using pass by value, pass
by reference and parameter arrays
Properties are always public and serves as the how external classes
will access the variables inside a class

32

You might also like