Visual Programming with Visual Programming with
Visual Basic .NETVisual Basic .NET
Procedures, Functions and StructuresProcedures, Functions and Structures
2
Procedures
Procedure
A block of statements enclosed by a declaration
statement and an End statement
Invoked from some other place in the code
When finished the execution, returns control to
the code that invoked it
Provide a way to break larger complex programs
into smaller and simple logical units – Divide and
conquer
Make code easier to read, understand and debug
Enable code reusability
Can be a sub procedure, function procedure or an
event procedure
Example
Boss assigns work to the workers
A worker may assign part of his work to a
subordinate
Once the given job is completed, boss can continue
with his work
How the worker does the work is not important here
3
Boss
Worker2
Worker4 Worker5
Worker3Worker1
Click Here for
more details
4
Sub Procedures
Sub procedure
A series of statements enclosed by the Sub and
End Sub statements
Performs actions but does not return a value to the
calling code
Can take arguments that are passed by the calling
code
Can define in modules, classes and structures
5
Declaration of Sub Procedures
Declaration syntax
[AccessSpecifier] Sub Identifier([ParameterList])
[Statements]
End Sub
AccessSpecifier could be Public, Protected, Friend,
or Private
If omitted, it is Public by default
Identifier specifies the identifier of the procedure
ParameterList is a comma-separated list of
parameters
Exit Sub statement can be used to exit immediately
from a Sub procedure
6
Declaration of Sub Procedures
Declaration syntax for Parameters [ByVal|
ByRef] Identifier As DataType
or Optional
[ByVal|ByRef] Identifier As DataType = _
DefaultValue
ByVal or ByRef specifies the argument passing
mechanism
If omitted, it is assumed ByVal by default
Optional indicates whether the argument is optional
If so, a default value must be declared for use in
case, if the calling code does not supply an argument
Parameters following a parameter corresponding to
an optional argument must also be optional
7
Argument Passing Mechanisms
Argument can be passed to a procedure by value
or by reference by specifying ByVal or ByRef
keywords, respectively
Passing by value means the procedure can not
modify the contents of arguments in calling code
Passing by reference allows the procedure to
modify the contents of arguments in calling code
Non-variable arguments in calling code are never
modified, even if they are passed by reference
8
Argument Passing Mechanisms
Passing arguments ByVal
Protects arguments from being changed by the
procedure
Affects to the performance due to the copying of
the entire data content of arguments to their
corresponding parameters
Passing arguments ByRef
Enables the procedure to return values to the
calling code through the arguments
Reduces the overhead of copying the arguments to
their corresponding parameters but can lead to an
accidental corruption of caller’s data
9
Function Procedures
Function procedure
A series of statements enclosed by the Function
and End Function statements
Similar to a Sub procedure, but can return a value
to the calling program
Can take arguments that are passed by the calling
code
Can define in modules, classes and structures
10
Declaration of Function Procedures
Declaration syntax
[AccessSpecifier] Function _
Identifier([ParameterList]) [As DataType]
[Statements]
Return ReturnExpression
End Function
AccessSpecifier could be Public, Protected, Friend,
or Private
If omitted, it is Public by default
Identifier specifies the identifier of the function
ParameterList is a comma-separated list of
parameters
DataType is the data type of ReturnExpression
11
Structures
Allows to create User Defined Data Types.
Once declared, a structure becomes a composite
data type and can declare variables of that
composite type
Like classes, can have data members and member
functions
Unlike classes
Structures are value type, not reference type
Can not inherit from another structure. So suitable
for objects which are more unlikely to extend
All members are Public by default
12
Declaration of Structures
Declaration syntax
[AccessSpecifier] Structure Identifier
MemberVariableDeclarations
[MemberFunctionDeclarations ]
End Structure
Can only be declared at module or class level
AccessSpecifier could be Public, Protected, Friend, or
Private
If omitted, it is Friend by default
Members could be Dim, Public, Friend, or Private, but
not Protected
Must contain at least one member variable
Member variables can’t be initialized at the declaration
Array members should be declared without the size.
Have to use ReDim to resize.
13
Variables of Composite Data Types
Variables of composite data types can be declared
with the data types defined as the structures
Declaration syntax
Dim Identifier As CompositeDataType
Can be used at method, class and module levels
Identifier specifies the identifier of the variable
CompositeDataType stands for structure defined
Possible to declare several variables of same type
or of different types in one statement
14
Using Composite Variables
Members of a composite variable can be accessed
with the period character
Syntax
CompositeVariable.Member
To set a value to a member variable
CompositeVariable.MemberVariable = Expression
To get the value in member variable
CompositeVariable.MemberVariable
To call a member function
CompositeVariable.MemberFunction ([ArgumentList])
Methods of Math Class
Function procedures (Methods) contained in class
“Math”
Performs mathematical operations and returns a
value
15
Method Description Example
Abs(x) Returns the absolute value of xAbs(-23.5) is 23.5
Ceiling(x)
Rounds x to the smallest integer
not less than x
Ceiling(9.2) is 10.0
Cos(x) Returns trigonometric cosine of xCos(0.0) is 1.0
Exp(x) Returns the exponential e
x
Exp(1.0) is
2.728281828459
05 approximately
Methods of Math Class
16
Method Description Example
Floor(x)
Rounds x to the largest integer not
greater than x
Floor(9.2) is 9.0
Log(x)
Returns the natural logarithm of x
(base e)
Log(2.718281828459
05) is 1.0 app.
Max(x,y) Returns the maximum value of x & yMax (5,8) is 8
Min(x,y) Returns the minimum value of x & yMin(5,8) is 5
Pow(x,y) Calculates x raised to power y
Pow(2.0,7.0) is
128
Sin(x) Returns the trigonometric sine of xSin(0.0) is 0.0
Sqrt(x) Returns the square root of x Sqrt(9.0) is 3.0
Tan(x)
Returns the trigonometric tangent
of x
Tan(0.0) is 0.0
Round(x)
Round(X, dp)
Rounds x. If given the # of decimal
places, it rounds to that decimal places
Round(2.3) is 2
Random Number Generation
What is a random number?
Dim RandomObject as Random = new Random()
Dim RandNum as Integer = RandomObject.Next()
This generates a positive Integer from 0 to
Int32.Maxvalue i.e. 2,147,483,647
We can give the range to produce random
numbers.
Value = randomobject.Next(1,7)
This returns a value between 1-6
If passed only one parameter, it will return a
value from 0 to the passed value but excluding
that value.
Rnd() returns a random number between 0 and 1
17
Methods of String Class
Two types
Shared Methods – No Need to mention the instance name
If Compare(strA,strB) > 0 Then …
Non shared Methods - Needs to mention the instance name
If myString.EndsWith(“ed”) Then …
18
Method Description
EndsWith(x) Checks whether the string instance ends with x
Equals(x) Checks whether the string instance equals x
Indexof(X) Returns the index where strinx x is found in the given string
Insert(startindex, X) X will be inserted into the given string starting at the given position
Remove(stIndx, NofChrs)Removes the given # of characters starting at the given position
Replace(oldstr, newstr)Replace the old string part with the new one
StartsWith(x) Checks whether the string instance starts with x
ToLower(), ToUpper() Converts to Lower Case or Upper Case
Trim(), TrimEnd(),
TrimStart()
Remove spaces from both sides, from start or from end
Functions to Determine Data Type
19
Method Description
IsArray(Variable Name) Checks whether the variable is an array
IsDate(Expression) Checks whether the expression is a valid data or time value
IsNumeric(Expression) Checks whether the expression evaluates to a numeric value
IsObject(variable Name)Checks whether the variable is an object
Is Nothing
Checks whether the object is set to nothing
If objMyObject Is Nothing Then …
TypeOf
Checks the type of an object variable
If TypeOf txtName is TextBox Then …
TypeName(Variable
Name)
Returns the data type of a non object type variable
Date / Time Functions
When a Date type variable is declared, CLR uses
the DateTime structure, which has an extensible
list of properties and methods
Now() and Today() are two shared members
Ex.
datToday = Today()
Non shared members could be used with the
instance name of the DateTime structure
20
Date / Time Functions
21
Method Description
Date Date Component
Day Integer day of month (1-31)
DayOfWeek Integer day of week ( 0 = Sunday)
DayOfYear Integer day of year ( 1-366)
Hour Integer hour (0-23)
Minute Integer minute (0-59)
Second Integer second (0-59)
Month Integer month ( 1 = January )
Year Year component
ToLongDateString Date formatted as long date
ToLongTimeString Date formatted as long time
ToShortDateStringDate formatted as short date
ToShortTimeStringDate formatted as short time
In Built String Functions
22
Function Description Example
InStr Finds the starting position of a substring
within a string
InStr(“My mother”, “mo”) = 4
LCase Converts a string to lower case LCase(“UPPER Case”) = upper case
Left Finds or removes a specified number of
characters from the beginning of a string
Left(“Kelaniya”, 6) = “Kelani”
Len Gives the length of a string Len(“Hello”) = 5
LTrim Removes spaces from the beginning of a
string
LTrim(“ Hello “) = “Hello “
Mid Finds or removes characters from a
string
Mid(“microsoft”,3,4) = “cros”
StrReverse Reverses the strings strReverse(“Kelaniya”) = “ayinaleK”
Right Finds or removes a specified number of
characters from the end of a string
Right(“Kelaniya”, 6) = “laniya”
RTrim Removes spaces from the end of a string RTrim(“ Hello “) = “ Hello“
Str Returns the string equivalent of a
number
Str(12345) = “12345”
Trim Trims spaces from both the beginning
and end of a string
Trim(“ Hello “) = “Hello“
UCase Converts a string to upper case UCase(“lower Case”) = “UPPER CASE”
Recursive Procedures
A procedure calls itself for a repetitive task
Ex. Calculating the Factorial Value
Any problem that can be solved recursively could
be solved iteratively
But recursions more naturally mirrors some
problems, hence easy to understand and debug
23
24
Classes
Standard programming unit in OOP
Encapsulate data members and member functions
into one package
Enable inheritance and polymorphism
Act as a template for creating objects
25
Declaration of Classes
Declaration syntax
[AccessSpecifier] Class Identifier
[Inherits BaseClass]
[MemberVariableDeclarations ]
[MemberFunctionDeclarations ]
End Class
AccessSpecifier could be Public, Protected, Friend,
or Private
If omitted, it is Friend by default
BaseClass specifies class that gives the inheritance
Members could be Dim, Public, Protected , Friend,
or Private
26
Modules
Like classes, encapsulate data members and
member functions defined within
Unlike classes, modules can never be instantiated
and do not support inheritance
Public members declared in a module are
accessible from anywhere in the project without
using their fully qualified names or an Imports
statement
Known as global members
Global variables and constants declared in a
module exist throughout the life of the program
27
Declaration of Modules
Declaration syntax
[AccessSpecifier] Module Identifier
[MemberVariableDeclarations ]
[MemberFunctionDeclarations ]
End Module
AccessSpecifier could only be Public or Friend
If omitted, it is Friend by default
Members could be Dim, Public, Protected , Friend,
or Private
28
Scope
Scope of a declared element is the region in which
it is available and can be referred without using
its fully qualified name or an Imports statement
Element could be a variable, constant, procedure,
class, structure or an enumeration
Use care when declaring elements with the same
identifier but with a different scope, because
doing so can lead to unexpected results
If possible, narrowing the scope of elements when
declaring them is a good programming practice
29
Block Level Scope
A block is a set of statements terminated by an
End, Else, Loop, or Next statement
An element declared within a block is accessible
only within that block
Element could be a variable or a constant
Even though scope of a block element is limited to
the block, it will exists throughout the procedure
that the block declared
30
Procedure Level Scope
Also referred to as method level scope
An element declared within a procedure is
accessible and available only within that
procedure
Element could be a variable or a constant
Known as local elements
All local variables should only be declared using
Dim as the access specifier and are Private by
default
31
Module Level Scope
Applies equally to modules, classes, and structures
Scope of an element declared within a module is
determined by the access specifier used at the
declaration
Elements at this level should be declared outside
of any procedure or block in the module
Element could be a variable, constant, procedure,
class, structure or an enumeration
Except for structures, variables declared using
Dim as the access specifier are Private by default
32
Accessibility of Elements
Accessibility of elements declared at module level
Public elements Accessible from
anywhere within the same project and from other
projects that reference the project
Friend elements
Accessible from within the same project, but not
from outside the project
Protected elements
Accessible only from within the same class, or from a
class derived from that class
Private elements
Accessible only from within the same module, class, or
structure